Leetcode 2437. Number of Valid Clock Times
You are given a string time in the form “HH:MM”, where some of the digits may be replaced by ‘?’. This string represents a time on a 24-hour clock (i.e., 00:00 to 23:59). Write a function to count the number of valid clock times possible by replacing each ‘?’ with a digit (0-9).
To solve the problem, we’ll take the following approach:
Here’s a step-by-step breakdown for each position in the string “HH:MM”:
HH, the valid hour ranges are from 00 to 23.
H1):
?, it can be 0, 1, or 2 depending on the second digit.H2):
0 or 1, it can be 0 to 9.2, it can be 0 to 3.MM, the valid minute ranges are from 00 to 59.
M1):
?, it can be 0 to 5.M2):
?, it can be 0 to 9.Let’s implement this strategy in C++:
#include <iostream>
#include <string>
using namespace std;
int countTime(string time) {
int count = 1;
if (time[0] == '?') {
if (time[1] == '?' || time[1] < '4') {
count *= 3; // '0', '1', '2'
} else {
count *= 2; // '0', '1'
}
}
if (time[1] == '?') {
if (time[0] == '2') {
count *= 4; // '0', '1', '2', '3'
} else if (time[0] == '?') {
count *= 10; // '0'-'9'
} else {
count *= 10; // '0'-'9'
}
}
if (time[3] == '?') {
count *= 6; // '0'-'5'
}
if (time[4] == '?') {
count *= 10; // '0'-'9'
}
return count;
}
int main() {
string time = "?4:5?";
cout << countTime(time) << endl; // Example usage
return 0;
}
The time complexity of this solution is O(1) since it involves a constant number of operations regardless of the input size. The input size is always fixed at 5 characters.
This code examines each position in the given time string and determines how many valid digits can replace the ‘?’ character:
HH, depending on the values of time[0] and time[1], different ranges of numbers are valid.MM, the ranges are more straightforward and depend on the range of valid minutes.Multiplying the number of choices for each position gives the total count of valid times.
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?