Skip to content
MediumBacktrackingAI interview only

Next Closest Time

Asked atgoogleamazonmeta

01 · Problem

You are given a 24-hour clock reading time in the form "HH:MM". Find the soonest moment strictly after time whose "HH:MM" representation is made up only of digits that already appear in time. Each available digit may be used any number of times.

The clock wraps around at midnight, so the answer may fall on the following day. If no other valid time can be formed, the answer is time itself (the same reading exactly 24 hours later).

Return the answer as a string in the same "HH:MM" format (two-digit hour 00-23, two-digit minute 00-59).

02 · Examples

Example 01
Input
time = "19:34"
Output
"19:39"

The digits available are 1, 9, 3 and 4. The first reachable time after 19:34 is 19:39, five minutes later. (19:35 to 19:38 need digits that are not available.)

Example 02
Input
time = "23:59"
Output
"22:22"

Nothing after 23:59 on the same day works, so we wrap past midnight. The earliest time built from {2, 3, 5, 9} on the next day is 22:22.

Example 03
Input
time = "13:55"
Output
"15:11"

With digits {1, 3, 5}, no minute value larger than 55 exists, and hour 14 is impossible, so the next hour is 15 with the smallest minute 11.

03 · Constraints

  • 01`time` has length 5 and matches the pattern `"HH:MM"`
  • 02`time` is a valid 24-hour time: `00 <= HH <= 23` and `00 <= MM <= 59`
  • 03The answer must be strictly later than `time` unless no other time can be formed, in which case return `time`

04 · Optimal complexity

Time
O(1)
Space
O(1)
05 · Two ways to work on it

Practice it alone or rehearse it as an interview.

Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.