#949

Largest Time for Given Digits

Medium
ArrayStringBacktrackingEnumerationBacktrackingEnumeration
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(24 * 60) = O(1)
O(1)
Space
O(1)
O(1)
💡

Intuition

Time O(1)Space O(1)

The optimal solution avoids generating all permutations by directly constructing valid times from the digits. It checks combinations that can form valid hours and minutes, significantly reducing unnecessary checks.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the input array to facilitate the formation of the largest time.
  2. 2Step 2: Iterate through all combinations of the first two digits as hours and the last two as minutes.
  3. 3Step 3: Validate the constructed time and keep track of the largest valid time found.
solution.py12 lines
1# Full working Python code
2import itertools
3
4def largestTimeFromDigits(arr):
5    arr.sort(reverse=True)
6    for i in range(24):
7        for j in range(60):
8            hh = f'{i:02}'
9            mm = f'{j:02}'
10            if all(d in arr for d in map(int, hh + mm)):
11                return f'{hh}:{mm}'
12    return ""

Complexity note: The time complexity is constant because we are iterating through a fixed number of possible times (1440). The space complexity is constant as well since we only store a few variables.

  • 1Sorting helps in quickly finding the largest possible time.
  • 2Validating time combinations reduces unnecessary checks.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.