Latest Time by Replacing Hidden Digits Problem
#1736
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1736.
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.
Example 1:
Input: time = "2?:?0"
Output: "23:50"
Explanation: The latest hour beginning with the digit '2' is 23 and the latest minute ending with the digit '0' is 50.
Example 2:
Input: time = "0?:3?"
Output: "09:39"
Example 3:
Input: time = "1?:22"
Output: "19:22"
Constraints:
timeis in the formathh:mm.- It is guaranteed that you can produce a valid time from the given string.
Solution
Approach: Greedy, One Digit at a Time
Each ? can be filled independently with the largest digit that still allows a valid time, so we go through the four digits and decide each by looking at its neighbours:
- First hour digit: if the second hour digit is known and is
4to9, the hour must start with1(24 to 29 are invalid). Otherwise use2. - Second hour digit: if the first hour digit is
2, the largest valid choice is3; otherwise (0or1) it is9. - First minute digit:
5. - Second minute digit:
9.
Rule 2 uses the first digit after it has been filled in, so we fix the digits from left to right.
Complexity: O(1) time and O(1) extra space, since the string has a fixed length of 5.
class Solution:
def maximumTime(self, time: str) -> str:
t = list(time)
if t[0] == '?':
t[0] = '1' if '4' <= t[1] <= '9' else '2'
if t[1] == '?':
t[1] = '3' if t[0] == '2' else '9'
if t[3] == '?':
t[3] = '5'
if t[4] == '?':
t[4] = '9'
return ''.join(t)