Python 0949.py
class Solution:
def largestTimeFromDigits(self, arr: List[int]) -> str:
result = ""
for p in permutations(arr):
hour = p[0] * 10 + p[1]
minute = p[2] * 10 + p[3]
if hour < 24 and minute < 60:
current = str(hour).zfill(2) + ":" + str(minute).zfill(2)
result = max(result, current)
return result
Difficulty
and has an acceptance rate of about 36% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Backtracking
- Enumeration
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a class Solution with a method largestTimeFromDigits that receives a list of four integers. The method explores every possible ordering of these four digits, interprets the first two as an hour and the last two as minutes, validates the resulting time, and keeps the lexicographically greatest valid representation. The final output is a string formatted as "HH:MM" or an empty string if no valid time exists.
Key Steps
Permutation Generation
The core of the algorithm relies on the permutations function from the standard library to enumerate all possible arrangements of the four input digits.
for p in permutations(arr):
Each iteration yields a tuple p containing a distinct ordering of the four digits, guaranteeing exhaustive coverage of the 4! = 24 possible configurations.
Time Construction and Validation
Within the loop, the first two elements of the permutation are combined to form an hour value, while the remaining two form a minute value. The arithmetic uses positional weighting to reconstruct the two-digit numbers.
hour = p[0] * 10 + p[1]
minute = p[2] * 10 + p[3]
A simple conditional checks whether the constructed hour is less than 24 and the minute is less than 60, which are the constraints for a valid 24-hour clock time.
if hour < 24 and minute < 60:
Result Formatting and Selection
When a permutation satisfies the time constraints, the hour and minute are converted to zero-padded two-character strings using zfill(2). The colon separator is inserted to produce the canonical "HH:MM" format.
current = str(hour).zfill(2) + ":" + str(minute).zfill(2)
The algorithm maintains a variable result that holds the greatest valid time encountered so far. Because the formatted strings are zero-padded, a direct lexical comparison using max correctly reflects chronological ordering.
result = max(result, current)
After all permutations have been examined, the method returns the stored result, which will be an empty string if no permutation satisfied the validation criteria.
return result
Edge Cases Handled
The implementation gracefully deals with inputs that cannot form any valid time. In such scenarios, the conditional if hour < 24 and minute < 60 never succeeds, leaving result unchanged from its initial empty string value. Consequently, the method returns an empty string, signaling the absence of a feasible time.
Zero-padding via zfill(2) ensures that times such as 0:5 are correctly represented as "00:05". This handling also guarantees that lexical comparison works uniformly across all possible times, including those with leading zeros.
When duplicate digits appear in the input list, permutations still generates all distinct positional arrangements, and the validation logic treats each arrangement independently. The algorithm therefore correctly accounts for repeated values without special casing.
Performance Optimizations
The code leverages built-in library functions that are implemented in C for speed. The use of permutations avoids manual nested loops, reducing interpreter overhead. By constructing the hour and minute with simple arithmetic rather than string concatenation, the method minimizes temporary object creation inside the loop.
Storing the best candidate as a string and updating it with max eliminates the need for separate numeric comparison or additional data structures. The zero-padded string format ensures that the lexical maximum directly corresponds to the latest possible time, allowing a single pass over the permutation space to determine the answer.
Overall, the solution achieves an efficient enumeration of the limited search space while keeping the inner loop lightweight, resulting in fast execution for the fixed-size input.
ELI5 - Simplified Explanation
Imagine having four numbered building blocks that you want to turn into a clock time. Since a clock needs hours and minutes, the code picks a random order for your four blocks to see if they can create a real time. It tests every possible mix of the blocks to find out which ones form a valid hour that is less than twenty-four and a valid minute that is less than sixty. Every time it finds a new valid time, it keeps the biggest one because that is the one that stays the latest in the day. It continues trying every single combination until it discovers the very largest time possible.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||
| WalkCCC | C++ | Java | Python | |||||
| leetcode.ca | C++ | Java | Python | Go | ||||
| LeetcodeHelp | C++ | Java | Python | |||||
| Progiez | C++ | Java | Python | |||||
| github | BigEggStudy | C# | ||||||
| black-shadows | C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| gouthampradhan | Java | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JS | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| varunu28 | Java | |||||||
| YuriSpiridonov | Python | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python | |||||||
| LeetcodeHelp | C++, Java, Python | |||||||
| Progiez | C++, Java, Python | |||||||
| BigEggStudy | C# | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| gouthampradhan | Java | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JavaScript | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| varunu28 | Java | |||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 2437: Number of Valid Clock Times
Solved On The Same Day
- problem 811: Subdomain Visit Count
- problem 900: RLE Iterator
- problem 945: Minimum Increment to Make Array Unique
- problem 1620: Coordinate With Maximum Network Quality
- problem 2240: Number of Ways to Buy Pens and Pencils
- problem 2249: Count Lattice Points Inside a Circle
- problem 2261: K Divisible Elements Subarrays
- problem 2310: Sum of Numbers With Units Digit K
- problem 2735: Collecting Chocolates
- problem 2800: Shortest String That Contains Three Strings
- problem 2306: Naming a Company
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality