Latest Time You Can Obtain After Replacing Characters Problem
Description
LeetCode Problem 3114.
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.
Example 1:
Input: s = "1?:?4"
Output: "11:54"
Explanation: The latest 12-hour format time we can achieve by replacing "?" characters is "11:54".
Example 2:
Input: s = "0?:5?"
Output: "09:59"
Explanation: The latest 12-hour format time we can achieve by replacing "?" characters is "09:59".
Constraints:
s.length == 5s[2]is equal to the character":".- All characters except
s[2]are digits or"?"characters. - The input is generated such that there is at least one time between
"00:00"and"11:59"that you can obtain after replacing the"?"characters.
Solution
Approach: Enumeration
Try every valid time from latest to earliest: hours 11 down to 0, minutes 59 down to 0. For each candidate HH:MM, check that it matches s at every position that is not ?. The first match is the answer.
Complexity: O(12 * 60) time, which is constant, and O(1) space.
class Solution:
def findLatestTime(self, s: str) -> str:
for h in range(11, -1, -1):
for m in range(59, -1, -1):
t = f"{h:02d}:{m:02d}"
if all(a == b for a, b in zip(s, t) if a != "?"):
return t