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.
For example:
time = "2?:?0"
, the function should return "23:50"
because the latest hour beginning with the digit '2' is 23 and the latest minute ending with the digit '0' is 50.time = "0?:3?"
, the function should return "09:39"
.time = "1?:22"
, the function should return "19:22"
.Write a function that takes a string time
as input and returns a string representing the latest valid time that can be obtained by replacing the '?' characters.
A brute-force approach would involve iterating through all possible times (00:00 to 23:59) and checking if each time matches the given pattern, where '?' can be any digit. The largest time that satisfies the condition would be the answer.
def solve():
time = input()
ans = ""
for h in range(24):
for m in range(60):
hh = str(h).zfill(2)
mm = str(m).zfill(2)
curr = hh + ":" + mm
ok = True
for i in range(5):
if time[i] == '?':
continue
if time[i] != curr[i]:
ok = False
break
if ok:
if ans == "" or curr > ans:
ans = curr
print(ans)
The optimal approach is to fill in the question marks from left to right, maximizing each digit while ensuring the resulting time is valid.
def maximum_time(time: str) -> str:
time_list = list(time)
if time_list[0] == '?':
if time_list[1] == '?' or int(time_list[1]) <= 3:
time_list[0] = '2'
else:
time_list[0] = '1'
if time_list[1] == '?':
if time_list[0] == '2':
time_list[1] = '3'
else:
time_list[1] = '9'
if time_list[3] == '?':
time_list[3] = '5'
if time_list[4] == '?':
time_list[4] = '9'
return "".join(time_list)
time
is guaranteed to be in the format "hhtime
is guaranteed to produce a valid time.