Problem 949

Abstract / Summary

Given four digits, find the largest valid time that can be formed in 24-hour format.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
11 lines | 405 bytes | submitted September 27, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 36% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Backtracking
  • Enumeration
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.22 | σ = 1.26

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
30 links | 18 authors | 7 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

12 solutions   September 27, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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