Latest Time by Replacing Hidden Digits - Problem
You're given a time string in the format hh:mm, but some digits are mysteriously hidden and replaced with ? characters! ๐Ÿ•ฐ๏ธ

Your mission is to maximize the time by strategically replacing each ? with the largest possible digit that still keeps the time valid. Valid times range from 00:00 to 23:59 (24-hour format).

Goal: Return the latest possible valid time by replacing all ? characters optimally.

Example: Given "2?:?0", you could make "20:50", "21:30", or "23:50" - but "23:50" is the latest valid time!

Input & Output

example_1.py โ€” Basic Hidden Digits
$ Input: time = "2?:?0"
โ€บ Output: "23:50"
๐Ÿ’ก Note: We need to replace two question marks. For position 1 (second hour digit), since the first hour digit is '2', the maximum valid value is '3' (making 23:xx). For position 3 (first minute digit), since the last minute digit is '0', we can use '5' to make xx:50. Final result: "23:50".
example_2.py โ€” Multiple Possibilities
$ Input: time = "?4:5?"
โ€บ Output: "14:59"
๐Ÿ’ก Note: For position 0 (first hour digit), since second hour digit is '4', we can use either '0' or '1' (04:xx or 14:xx), but '1' gives us a later time. For position 4 (second minute digit), we can use '9' to maximize minutes. Result: "14:59".
example_3.py โ€” All Hidden
$ Input: time = "??:??"
โ€บ Output: "23:59"
๐Ÿ’ก Note: When all digits are hidden, we want the latest possible time. Maximum valid hour is 23, maximum valid minutes is 59. So we get "23:59" which is the latest time in 24-hour format.

Constraints

  • time is in the format hh:mm
  • It is guaranteed that you can produce a valid time from the given string
  • The string length is always 5 characters
  • Valid times are between 00:00 and 23:59

Visualization

Tap to expand
๐Ÿ•ฐ๏ธ Digital Clock Repair Simulation2?:?0Constraint CheckHour: 2? โ†’ 23Max valid: 23:59Optimal ChoiceMinute: ?0 โ†’ 50Maximize: 5 + 0Final Result23:50โœ… REPAIRED: 23:50
Understanding the Visualization
1
Identify Broken Segments
The clock shows "2?:?0" - two digits are broken and need replacement
2
Fix Hour Display
Since first hour digit is '2', second digit can be max '3' (making 23:xx)
3
Fix Minute Display
Since last minute digit is '0', first minute digit can be max '5' (making xx:50)
4
Final Time
Clock now displays "23:50" - the latest possible valid time!
Key Takeaway
๐ŸŽฏ Key Insight: By using a greedy approach and understanding time format constraints, we can optimally replace each '?' with the maximum valid digit, achieving O(1) time complexity.
Asked in
Amazon 15 Google 8 Microsoft 6 Meta 4
28.3K 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