Leetcode 1736. Latest Time by Replacing Hidden Digits
You are given a string time
in the form of “HH:MM”, where some of the digits in the string are represented by ‘?’. The question marks represent digits that need to be replaced to convert time
into the latest possible valid 24-hour time. Return the latest valid time in the “HH:MM” format.
00
to 23
and minutes from 00
to 59
.[0-9]
or ‘?’.To find the latest valid time by replacing ‘?’, we need to consider the following:
time[0]
):
time[1]
) is between '0'
and '3'
(inclusive), the first digit can be 2
to maximize.1
.time[1]
):
2
, the second digit can be between 0
and 3
.9
.time[3]
), the maximum possible value is 5
.time[4]
), the maximum value is 9
.#include <iostream>
#include <string>
std::string maximumTime(std::string time) {
// Process hours
if (time[0] == '?') {
if (time[1] != '?' && time[1] > '3') {
time[0] = '1';
} else {
time[0] = '2';
}
}
if (time[1] == '?') {
if (time[0] == '2') {
time[1] = '3';
} else {
time[1] = '9';
}
}
// Process minutes
if (time[3] == '?') {
time[3] = '5';
}
if (time[4] == '?') {
time[4] = '9';
}
return time;
}
int main() {
std::string time;
std::cin >> time;
std::cout << maximumTime(time) << std::endl;
return 0;
}
The time complexity of this solution is O(1), as the operations to replace the ‘?’ characters involve a constant amount of work regardless of the input size.
This solution maximizes the given time string to the latest possible valid time while ensuring all replacements lead to a valid 24-hour time format.
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?