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
00to23 - Minutes range from
00to59 - 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
timeis 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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code