Latest Time by Replacing Hidden Digits - Problem

You are given a string time in the form of hh:mm, where some of the digits in the string are hidden (represented by ?).

The valid times are those inclusively between 00:00 and 23:59.

Return the latest valid time you can get from time by replacing the hidden digits.

Input & Output

Example 1 — Missing Hour and Minute
$ Input: time = "2?:?0"
Output: "23:50"
💡 Note: First hour digit is given as 2, so second can be max 3 (giving 23). First minute digit can be max 5, second is given as 0.
Example 2 — Missing All Digits
$ Input: time = "??:??"
Output: "23:59"
💡 Note: All digits are missing, so we choose maximum for each: 2, 3, 5, 9 giving 23:59.
Example 3 — First Hour Digit Forces Constraint
$ Input: time = "0?:??"
Output: "09:59"
💡 Note: First hour digit is 0, so second can be max 9. Minutes can be max 59.

Constraints

  • time is in the format hh:mm
  • It is guaranteed that you can generate a valid time from the given string

Visualization

Tap to expand
Latest Time by Replacing Hidden DigitsInput2?:?0Maximize DigitsOutput23:50Missing: positions 1,3Max valid: 2→3, ?→5? at position 1: max 3 (since first digit is 2)? at position 3: max 5 (first minute digit)
Understanding the Visualization
1
Input
Time string with ? for missing digits
2
Process
Replace each ? with maximum valid digit
3
Output
Latest possible valid time
Key Takeaway
🎯 Key Insight: Greedily choose the maximum valid digit at each position based on 24-hour time constraints
Asked in
Google 15 Amazon 12 Microsoft 8
28.0K Views
Medium Frequency
~8 min Avg. Time
892 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