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:
time
is in the format hh:mm
.Given a string time
representing time in "hh:mm" format, where some digits are hidden ('?'), find the latest valid time by replacing the hidden digits. Valid times are between 00:00 and 23:59.
The most efficient way to solve this problem is using a greedy approach. We iterate through the time string and fill in the '?' characters one by one, always choosing the largest possible digit while ensuring the resulting time is valid.
Here's a breakdown of the approach:
Hours:
time[0]
) is '?', we check the second digit (time[1]
):
time[1]
is between '4' and '9', the largest possible first digit is '1'.time[1]
) is '?', we check the first digit (time[0]
):
time[0]
is '2', the largest possible second digit is '3'.Minutes:
time[3]
) is '?', the largest possible digit is '5'.time[4]
) is '?', the largest possible digit is '9'.class Solution:
def maximumTime(self, time: str) -> str:
time_list = list(time)
if time_list[0] == '?':
time_list[0] = '2' if time_list[1] == '?' or int(time_list[1]) < 4 else '1'
if time_list[1] == '?':
time_list[1] = '9' if time_list[0] == '1' or time_list[0] == '?' else '3'
if time_list[3] == '?':
time_list[3] = '5'
if time_list[4] == '?':
time_list[4] = '9'
return "".join(time_list)
class Solution {
public String maximumTime(String time) {
char[] timeArray = time.toCharArray();
if (timeArray[0] == '?') {
timeArray[0] = (timeArray[1] == '?' || timeArray[1] < '4') ? '2' : '1';
}
if (timeArray[1] == '?') {
timeArray[1] = (timeArray[0] == '2') ? '3' : '9';
}
if (timeArray[3] == '?') {
timeArray[3] = '5';
}
if (timeArray[4] == '?') {
timeArray[4] = '9';
}
return new String(timeArray);
}
}
/**
* @param {string} time
* @return {string}
*/
var maximumTime = function(time) {
let timeArray = time.split('');
if (timeArray[0] === '?') {
timeArray[0] = (timeArray[1] === '?' || parseInt(timeArray[1]) < 4) ? '2' : '1';
}
if (timeArray[1] === '?') {
timeArray[1] = (timeArray[0] === '2') ? '3' : '9';
}
if (timeArray[3] === '?') {
timeArray[3] = '5';
}
if (timeArray[4] === '?') {
timeArray[4] = '9';
}
return timeArray.join('');
};
The solution efficiently determines the latest possible valid time by making greedy choices based on the available digits and constraints. The constant time and space complexity makes it highly efficient for this specific problem.