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 Digits INPUT Time String Format: hh:mm 2 ? : ? 0 h1 h2 m1 m2 time = "2?:?0" Valid Time Range: 00:00 - 23:59 ? = hidden digit Goal: Find LATEST time = Unknown digit ALGORITHM STEPS 1 Process h1 (first digit) h1=2 (fixed), keep as is 2 2 Process h2 (second digit) h2=? and h1=2, max is 3 (since 24:xx is invalid) 3 3 Process m1 (third digit) m1=?, max minute tens = 5 (since 60+ mins invalid) 5 4 Process m2 (fourth digit) m2=0 (fixed), keep as is 0 Greedy Strategy: For each ?, pick the LARGEST valid digit to maximize time FINAL RESULT 23:50 Transformation: 2?:?0 --> 23:50 Verification: [OK] 23 is in range [00-23] [OK] 50 is in range [00-59] [OK] Latest possible time Output: "23:50" Key Insight: The greedy approach works because each digit position is independent once we know the constraints. For hours: if h1=2, then h2 can only be 0-3. If h1 is 0 or 1, h2 can be 0-9. For minutes: m1 can only be 0-5, m2 can be 0-9. Always choose maximum valid digit for latest time. TutorialsPoint - Latest Time by Replacing Hidden Digits | Greedy Approach
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