Next Closest Time - Problem

Imagine you're working on a digital clock application that has a unique constraint: the display can only show digits that are already present in the current time.

Given a time in the format "HH:MM" (24-hour format), your task is to find the next closest time by rearranging and reusing only the existing digits. You can reuse any digit multiple times, but you cannot introduce new digits.

Important rules:

  • Time format is always "HH:MM" (e.g., "01:34", "23:59")
  • Hours range from 00 to 23
  • Minutes range from 00 to 59
  • If no valid next time exists on the same day, wrap around to the next day

Example: Given "19:34", the available digits are [1, 9, 3, 4]. The next closest time using these digits would be "19:39".

Input & Output

example_1.py โ€” Basic increment
$ Input: "19:34"
โ€บ Output: "19:39"
๐Ÿ’ก Note: Available digits are [1,9,3,4]. The next closest time can be formed by changing the last digit from 4 to 9, giving us 19:39.
example_2.py โ€” Wraparound to next day
$ Input: "23:59"
โ€บ Output: "22:22"
๐Ÿ’ก Note: Available digits are [2,3,5,9]. No valid time exists after 23:59 on the same day, so we find the smallest valid time for the next day: 22:22.
example_3.py โ€” All same digits
$ Input: "11:11"
โ€บ Output: "11:11"
๐Ÿ’ก Note: Only digit 1 is available. The next valid time using only 1s is 11:11 (wraps around to the next day).

Constraints

  • The input time is in the format "HH:MM"
  • Hours are in range [00, 23]
  • Minutes are in range [00, 59]
  • All digits in the result must be present in the original time
  • Return the lexicographically next closest time

Visualization

Tap to expand
Digital Clock - Next Valid Time19:34Available Digits: 1, 9, 3, 4Increment Strategy:Position 3 (minutes units): 4 โ†’ next is 9 โœ“Positions 0,1,2 unchanged: 1,9,3NEXT TIME19:39โšก O(1) Time๐ŸŽฏ Smart Strategy
Understanding the Visualization
1
Identify Working Segments
Extract all unique digits from current time - these are the only segments that work
2
Smart Increment Strategy
Try to increment the rightmost position first (minutes units), then move left
3
Validate Time Constraints
Ensure each position respects time limits (hours: 00-23, minutes: 00-59)
4
Handle Overflow
If no valid time exists today, wrap to next day with smallest valid time
Key Takeaway
๐ŸŽฏ Key Insight: Instead of brute-force checking every minute, we strategically increment time positions from right to left, respecting digit availability and time constraints for optimal O(1) performance.
Asked in
Google 42 Amazon 38 Facebook 31 Microsoft 25
78.6K Views
Medium Frequency
~18 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen