Next Closest Time - Problem

Given a time represented in the format "HH:MM", form the next closest time by reusing the current digits. There is no limit on how many times a digit can be reused.

You may assume the given input string is always valid. For example, "01:34", "12:09" are all valid. "1:34", "12:9" are all invalid.

Return the next closest time in the same format "HH:MM".

Input & Output

Example 1 — Basic Case
$ Input: time = "19:34"
Output: "19:39"
💡 Note: The next closest time using digits {1,3,4,9} is 19:39. We increment the minutes from 34 to 39 using available digits.
Example 2 — Wrap to Next Hour
$ Input: time = "23:59"
Output: "22:22"
💡 Note: Available digits are {2,3,5,9}. Since no valid time exists after 23:59 on same day using these digits, we wrap to next day with smallest time: 22:22.
Example 3 — Same Digits
$ Input: time = "00:00"
Output: "00:00"
💡 Note: Only digit 0 is available. The next closest time using only 0s is still 00:00 (wraps around).

Constraints

  • time.length == 5
  • time is in the format "HH:MM"
  • 0 ≤ HH ≤ 23
  • 0 ≤ MM ≤ 59

Visualization

Tap to expand
Next Closest Time - Smart Digit Replacement INPUT 19:34 Available Digits: 1 3 4 9 (Sorted: 1, 3, 4, 9) Digit Positions: pos[0]=1, pos[1]=9 pos[2]=3, pos[3]=4 HH: 00-23, MM: 00-59 Format: "HH:MM" ALGORITHM STEPS 1 Extract & Sort Digits Get unique digits: {1,3,4,9} 2 Scan Right to Left Find replaceable digit pos[3]=4: next larger? 9 (invalid) pos[2]=3: next larger? 4 (valid!) --> Replace 3 with 4 3 Replace Digit Minute tens: 3 --> 4 4 Fill Rest with Min Remaining positions: min(1) 19:41 (minute unit = 1) FINAL RESULT 19:41 +7 minutes Verification: Digits used: 1, 9, 4, 1 All from {1, 3, 4, 9}: OK Valid time (19:41): OK Next closest: OK Output: "19:41" Key Insight: Smart Digit Replacement scans from right to left, finding the rightmost digit that can be replaced with a larger available digit while keeping the time valid. All remaining positions get the smallest digit. If no replacement found, wrap to midnight using minimum digits. Time Complexity: O(1), Space: O(1) TutorialsPoint - Next Closest Time | Smart Digit Replacement Approach
Asked in
Google 25 Facebook 18 Amazon 12
32.0K Views
Medium Frequency
~25 min Avg. Time
850 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