Latest Time You Can Obtain After Replacing Characters - Problem

You are given a string s representing a 12-hour format time where some of the digits (possibly none) are replaced with a "?".

12-hour times are formatted as "HH:MM", where HH is between 00 and 11, and MM is between 00 and 59.

The earliest 12-hour time is 00:00, and the latest is 11:59.

You have to replace all the "?" characters in s with digits such that the time we obtain by the resulting string is a valid 12-hour format time and is the latest possible.

Return the resulting string.

Input & Output

Example 1 — Basic Case
$ Input: s = "1?:?9"
Output: "11:59"
💡 Note: Replace first '?' with '1' to get maximum hour 11, and second '?' with '5' to get maximum minute 59. Result: 11:59 is the latest valid time.
Example 2 — All Question Marks
$ Input: s = "??:??"
Output: "11:59"
💡 Note: All positions are flexible. Choose maximum valid digits: hour = 11 (max hour), minute = 59 (max minute). Result: 11:59.
Example 3 — Hour Constraint
$ Input: s = "0?:??"
Output: "09:59"
💡 Note: First hour digit is 0, so second can be at most 9 (giving 09). Minutes can be maximized to 59. Result: 09:59.

Constraints

  • s.length == 5
  • s[2] == ':'
  • All other characters in s are digits or '?'

Visualization

Tap to expand
Latest Time You Can Obtain After Replacing Characters INPUT Input String s: 1 ? : ? 9 H1 H2 M1 M2 = Unknown (?) = Known digit 12-Hour Format Rules - HH: 00 to 11 - MM: 00 to 59 - Earliest: 00:00 - Latest: 11:59 ALGORITHM STEPS 1 Check Position 0 (H1) s[0]='1' is valid, keep it 1 2 Check Position 1 (H2) s[1]='?' and s[0]='1' Max valid = 1 (for 11) 1 3 Check Position 3 (M1) s[3]='?', maximize to 5 (max tens digit for min) 5 4 Check Position 4 (M2) s[4]='9' is valid, keep it 9 Greedy Strategy: Process left to right. Replace ? with max valid digit. FINAL RESULT Output String: 1 1 : 5 9 = Replaced digit = Original digit Verification Hour: 11 (valid: 00-11) OK Minute: 59 (valid: 00-59) OK Is Latest Possible? YES "11:59" Key Insight: The greedy approach works because we process digits left to right, maximizing each position independently. For hours (HH): if H1 is 0, H2 can be 0-9; if H1 is 1, H2 can only be 0-1. For minutes: M1 is 0-5, M2 is 0-9. TutorialsPoint - Latest Time You Can Obtain After Replacing Characters | Greedy Approach
Asked in
Google 15 Amazon 12
25.0K Views
Medium Frequency
~15 min Avg. Time
890 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