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 by Replacing CharactersInput: "1?:?9"Time with missing digitsReplace with Max ValidOutput: "11:59"Latest possible timePosition 1: ? → 1Position 3: ? → 5Greedy Choice: Pick maximum valid digit for each position
Understanding the Visualization
1
Input
Time string with '?' characters: "1?:?9"
2
Process
Replace each '?' with the largest valid digit
3
Output
Latest valid time: "11:59"
Key Takeaway
🎯 Key Insight: Use greedy strategy - each position independently chooses the maximum valid digit
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