Largest Time for Given Digits solution explained
Largest Time for Given Digits is best solved by trying all 24 orderings of the four digits, keeping each one whose first pair is under 24 and second pair is under 60, and returning the latest as HH:MM, or an empty string if none is valid. The work is constant, and unlike a digit-by-digit greedy, it cannot miss a case.
By Evin JohnPublished 7 min read
What you are asked to do
You get exactly four single digits. Place all four into the pattern HH:MM to make a time on a 24-hour clock, where hours run from 00 to 23 and minutes from 00 to 59. Return the latest such time as a five-character string. If no arrangement makes a valid time, return an empty string.
| Digits | Latest time | Comment |
|---|---|---|
| 1, 9, 4, 7 | 19:47 | No hour in the twenties is possible, so 19 leads. |
| 2, 3, 5, 9 | 23:59 | The latest time on the clock. |
| 2, 4, 0, 0 | 20:40 | 24 is not a valid hour, so the hour drops to 20. |
| 0, 2, 6, 6 | 06:26 | Two sixes cannot both sit in the minutes' tens place or the hour. |
| 7, 7, 8, 9 | (empty string) | Every hour would start with 7 or more. |
| 0, 0, 0, 0 | 00:00 | Midnight is valid. |
Check the expected output format before coding. Leading zeros matter: six past midnight is 00:06, not 0:6. Also ask whether a 24:00 notation counts, since some systems use it. The usual answer is no, and that is what this page assumes.
What makes it worth asking
The search space is tiny, which is the lesson. Strong candidates see that 24 orderings can simply be enumerated and stop there. Weaker answers build a clever greedy, miss a case, and spend the rest of the round patching it. Interviewers use this to see whether you can tell when brute force is the right answer.
The obviously correct check: count down the clock
A day has 1,440 minutes. Start at 23:59 and move backward one minute at a time. For each time, write out its four digits, sort them, and compare with the sorted input. The first match is the answer. If you reach 00:00 without a match, return an empty string. This is constant time too, just with a larger constant, and it is easy to trust.
def latest_time_countdown(digits):
want = sorted(digits)
for t in range(24 * 60 - 1, -1, -1):
h, m = divmod(t, 60)
if sorted([h // 10, h % 10, m // 10, m % 10]) == want:
return "%02d:%02d" % (h, m)
return ""Main approach: all 24 orderings
Four distinct positions can be filled in 4 × 3 × 2 × 1 = 24 ways. For each ordering, read the first two digits as the hour and the last two as the minute. Skip it if the hour is 24 or more or the minute is 60 or more. Otherwise convert it to minutes since midnight and keep the maximum. Comparing a single integer avoids comparing hours and minutes separately and makes the code shorter.
Duplicates in the input are harmless. Some orderings will repeat, but the result is the same, and 24 iterations is nothing.
from itertools import permutations
def latest_time(digits):
best = -1
for a, b, c, d in permutations(digits):
hours, minutes = a * 10 + b, c * 10 + d
if hours < 24 and minutes < 60:
best = max(best, hours * 60 + minutes)
if best < 0:
return ""
return "%02d:%02d" % divmod(best, 60)function latestTime(digits) {
let best = -1;
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 4; j++) {
if (j === i) continue;
for (let k = 0; k < 4; k++) {
if (k === i || k === j) continue;
const l = 6 - i - j - k;
const hours = digits[i] * 10 + digits[j];
const minutes = digits[k] * 10 + digits[l];
if (hours < 24 && minutes < 60) {
best = Math.max(best, hours * 60 + minutes);
}
}
}
}
if (best < 0) return "";
const hh = String(Math.floor(best / 60)).padStart(2, "0");
const mm = String(best % 60).padStart(2, "0");
return hh + ":" + mm;
}The index trick works because 0 + 1 + 2 + 3 = 6, so once three distinct indexes are fixed the fourth is forced. It saves a fourth loop and a check, and it is worth one sentence of explanation so the interviewer does not think it is magic.
Why the greedy shortcut breaks
A tempting plan fills the slots left to right, each time taking the largest remaining digit that keeps the time valid so far: hour tens at most 2, hour ones at most 3 if the tens digit is 2, minute tens at most 5. On 0, 2, 6, 6 it takes 2 for the hour tens and 0 for the hour ones, giving 20, then needs a minute tens digit of 5 or less from 6 and 6, and fails. The correct answer, 06:26, needs a smaller hour to leave a usable digit for the minutes. You can patch the greedy with backtracking, but by then it is a slower way of writing the 24-ordering loop.
Running time
| Approach | Work done | Memory | Risk |
|---|---|---|---|
| Countdown over the day | Up to 1,440 sorted comparisons | O(1) | Very low |
| All 24 orderings | 24 checks | O(1) | Very low |
| Greedy slot by slot | A handful of steps | O(1) | Wrong on some inputs unless it backtracks |
Big O labels all of these O(1), since the input size never changes. Say that, and then explain that the constant still matters for clarity and correctness rather than for speed.
Edge cases
- All zeros: 00:00, the earliest valid time, still counts as an answer.
- No digit below 3: no valid hour exists, so return an empty string.
- Too many large digits, such as 1, 7, 8, 9: the hour 17, 18 or 19 works, but the remaining two digits must form minutes under 60, and none can.
- Duplicates like 1, 1, 1, 1: only 11:11 is possible.
- An hour of exactly 24 or a minute of exactly 60: both must be rejected with strict less-than checks.
Where people lose points
- Writing the greedy and defending it after a counterexample appears.
- Using less-than-or-equal and accepting 24:00 or 12:60.
- Forgetting zero-padding, so 06:26 prints as 6:26.
- Comparing candidate times as strings without padding, where 9:59 sorts after 19:00.
- Generating permutations of values instead of positions, then dropping a duplicate digit by accident when using a set.
Variations to expect
- Earliest valid time. Keep the minimum instead of the maximum.
- Six digits with seconds. 720 orderings still enumerate instantly; add a seconds check below 60.
- Next closest time using the same digits. Count forward one minute at a time from the given time and return the first whose digits all come from the allowed set, wrapping past midnight.
The answer in conversation
Fictional example
- Candidate
- There are only 24 ways to order four digits, so I will try them all rather than reason about which digit goes where.
- Candidate
- For each ordering I check hours below 24 and minutes below 60, convert to minutes since midnight, and keep the maximum.
- Candidate
- A slot-by-slot greedy is tempting, but it fails on 0, 2, 6, 6, because a big hour can leave no valid minutes.
Next in this set
Largest Number asks a related question without the clock limits, and its comparator is worth knowing. Custom Sort String moves on to ordering characters by a rule you are given. The algorithm interview questions guide covers when brute force is the right call.
Rehearse with Natively
In practice, Natively can pick up a problem like this from a screenshot, read it and suggest an approach along with code, so you can test your instinct about brute force against another view. It also writes a transcript of a mock round on your computer, which makes it easy to spot whether you named the greedy trap aloud. See an AI interview assistant for Mac and Windows.
Questions people ask
How do you solve Largest Time for Given Digits?
Try every ordering of the four digits, 24 in total. Treat the first two as hours and the last two as minutes, keep only hours under 24 and minutes under 60, and return the latest one as HH:MM, or an empty string if none is valid.
Why doesn't a greedy digit-by-digit approach work?
Choosing the largest possible hour first can use up the digits the minutes need. With 0, 2, 6, 6 the greedy builds 20 and then cannot make valid minutes, while 06:26 is the right answer.
What is the time complexity?
O(1). The input always has four digits, so there are always 24 orderings to check, and memory use is constant.
How should the result be formatted?
As HH:MM with two digits for each part, so leading zeros are kept, for example 06:26 or 00:00. Return an empty string when no valid time exists.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
