Magicsheet logo

Next Closest Time

Medium
25%
Updated 8/1/2025

Next Closest Time

What is this problem about?

The Next Closest Time problem gives you a time string "HH:MM". Using only the digits present in this string (repetition allowed), find the next valid time that is closest to the given time but strictly later (wrapping midnight if needed). This Next Closest Time coding problem uses enumeration over all possible digit combinations to find the answer.

Why is this asked in interviews?

Google asks this as a clever enumeration problem that tests careful time validation logic and knowledge of the constraint set. The hash table, enumeration, backtracking, and string interview pattern is demonstrated here, and the problem rewards candidates who can enumerate all valid times efficiently (there are only 24*60 = 1440 possible minutes).

Algorithmic pattern used

Minute enumeration from current time. Extract the four digits available. Starting from current_time + 1 minute, check each subsequent minute (wrapping at 1440). For each candidate time, verify that all four of its digits (HH:MM) are in the set of available digits. Return the first valid candidate found.

Example explanation

Time: "19:34". Available digits: {1, 9, 3, 4}. Current minutes = 19*60+34 = 1174. Check 1175 (19:35): digit 5 not available. Check... continue until finding a valid time. 19:39? '9','3','9': all in {1,9,3,4}? '9','3','9' → 19:39. ✓ Return "19:39".

Common mistakes candidates make

  • Generating all digit combinations (4^4 = 256) without validating time constraints (hours 00-23, minutes 00-59).
  • Not handling the midnight wrap-around (after 23:59 → 00:00).
  • Checking digits as characters vs integers (format consistency matters).
  • Returning the same time instead of strictly next time.

Interview preparation tip

When an enumeration space is small (1440 minutes per day), exhaustive enumeration with validity checks is clean and O(1440) time. For this problem, the "iterate from current+1, wrap at 1440" approach avoids complex case analysis. Practice time-validation functions: hours = minutes // 60, mins = minutes % 60, format as f"{h:02d}:{m:02d}". Digit validation is a simple set membership check. Simple, correct enumeration beats complex but buggy constructive approaches.

Similar Questions