You are given a time in the format of HH:MM, where some of the digits are hidden (represented by ?). The task is to replace the hidden digits in such a way that the resulting time is the latest possible valid time. The given string will always satisfy the format HH:MM.
"?4:5?""14:59""23:5?""23:59""2?:22""23:22"HH:MM with exactly two characters for hours and two for minutes?
? characters will be used as placeholders.To solve this problem, we need to consider how to replace each ? to create the maximum possible time:
HH):
?, it can be either 2 if the second digit is 0-3, or 1 if the second digit is 4-9.?, it can be 9 if the first digit is 0 or 1, or 3 if the first digit is 2.MM):
? with the highest possible valid digit (9).def maximumTime(time: str) -> str:
hours, minutes = time.split(":")
# Handle hours
if hours[0] == "?":
if hours[1] == "?" or int(hours[1]) <= 3:
hours = "2" + hours[1]
else:
hours = "1" + hours[1]
if hours[1] == "?":
if hours[0] == "2":
hours = hours[0] + "3"
else:
hours = hours[0] + "9"
# Handle minutes
if minutes[0] == "?":
minutes = "5" + minutes[1]
if minutes[1] == "?":
minutes = minutes[0] + "9"
return f"{hours}:{minutes}"
# Example usage
print(maximumTime("?4:5?")) # Should return "14:59"
print(maximumTime("23:5?")) # Should return "23:59"
print(maximumTime("2?:22")) # Should return "23:22"
This code efficiently finds and replaces the ? characters, ensuring the resulting time is the latest possible valid time.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?