Number of Valid Clock Times solution and explanation
9 more videos on this problem
2437. Number of Valid Clock Times (Leetcode Easy)Programming Live with Larry · 4:05 · 686 views
2437. Number of Valid Clock Times || Leetcode Contest Easy || CPPCoding Techniques with Komal | Newton School · 12:42 · 493 views
Number of Valid Clock Times || leetcode Biweekly 89 || Leetcode EasyBinaryMagic · 10:57 · 432 views
Leetcode BiWeekly contest 89 - Easy - Number of Valid Clock TimesPrakhar Agrawal · 10:29 · 400 views
Number of Valid Clock Times||leetcodePrasun kumar · 0:13 · 227 views
LeetCode 2437 | Number of Valid Clock Times | Math | JavaSleepy Cracker · 7:44 · 214 views
6208. Number of Valid Clock Times||Leetcode biweekly contest-89 || C++ || Code in DescriptionCS warriors · 11:15 · 174 views
Number of Valid Clock Times || LeetCode Biweekly || C++Priyanshi Porwal · 4:59 · 157 views
Number of Valid Clock Times|| solution ||leetcodePrasun kumar · 0:35 · 59 views
Number of Valid Clock Times || leetcode biweekly contest 89ZiddiCoder · 14:32 · 45 views
The problem
You are given a string of length 5 called time, representing the current time on a digital clock in the format "hh:mm". The earliest possible time is "00:00" and the latest possible time is "23:59".
In the string time, the digits represented by the ? symbol are unknown, and must be replaced with a digit from 0 to 9.
Return an integer answer, the number of valid clock times that can be created by replacing every ? with a digit from 0 to 9.
Example 1:
Input: time = "?5:00" Output: 2 Explanation: We can replace the ? with either a 0 or 1, producing "05:00" or "15:00". Note that we cannot replace it with a 2, since the time "25:00" is invalid. In total, we have two choices.
Example 2:
Input: time = "0?:0?" Output: 100 Explanation: Each ? can be replaced by any digit from 0 to 9, so we have 100 total choices.
Example 3:
Input: time = "??:??" Output: 1440 Explanation: There are 24 possible choices for the hours, and 60 possible choices for the minutes. In total, we have 24 * 60 = 1440 choices.
Constraints:
timeis a valid string of length5in the format"hh:mm"."00" <= hh <= "23""00" <= mm <= "59"- Some of the digits might be replaced with
'?'and need to be replaced with digits from0to9.
Approach overview
Problem Overview: You receive a time string in the format hh:mm where some digits may be replaced with ?. Each ? can represent any digit. The task is to count how many valid 24‑hour clock times (00:00–23:59) can be formed by replacing the unknown characters.
Approach 1: Brute Force Enumeration (O(1440) time, O(1) space)
The simplest strategy is to enumerate every possible valid time in a 24‑hour day. There are only 24 * 60 = 1440 combinations. Iterate through all hours from 00 to 23 and minutes from 00 to 59, convert each candidate into a string, and compare it with the input pattern. A candidate is valid if every non‑? character in the input matches the corresponding digit in the generated time. This approach uses straightforward enumeration and simple string comparison. Since the search space is fixed (1440), the runtime is effectively constant and trivial to implement in any language.
Approach 2: Character-Specific Enumeration (O(1) time, O(1) space)
Instead of checking every full time, compute the number of valid options for the hour and minute positions independently. For minutes, the first digit can be 0–5 and the second 0–9, adjusted based on whether the input contains a fixed digit or ?. Hours require slightly more logic because the valid range is 00–23. If both hour digits are ?, there are 24 possibilities. If only the first digit is ?, the second digit determines whether the first can be 0–2 or only 0–1. If only the second digit is ?, the allowed range depends on whether the first digit is 2 (then 0–3) or 0–1 (then 0–9). Multiply the number of valid hour combinations by the number of valid minute combinations. This direct counting method leverages constraints of the clock format and avoids scanning all possibilities.
Recommended for interviews: Start with the brute force enumeration to show you understand the valid time space (1440 possibilities). Then mention the character‑specific counting approach, which computes the answer in constant time by analyzing each digit position. Interviewers typically expect the optimized counting logic because it demonstrates strong reasoning about constraints and efficient enumeration without unnecessary iteration.
Approach 1: Brute Force Enumeration
In this approach, we iterate over all possible valid hours and minutes, checking if a given configuration of the time string with '?' replaced can form a valid time. The constraints allow us to simply enumerate the values and check against the string.
def valid_clock_times(time: str) -> int:
count = 0
for h in range(24):
for m in range(60):
hh = f'{h:02}'
mm = f'{m:02}'
if (time[0] == '?' or time[0] == hh[0]) and \
(time[1] == '?' or time[1] == hh[1]) and \
(time[3] == '?' or time[3] == mm[0]) and \
(time[4] == '?' or time[4] == mm[1]):
count += 1
return count
time_example = "?5:00"
print(valid_clock_times(time_example)) # Outputs: 2public class ValidClockTimes {
public static int validClockTimes(String time) {
int count = 0;
for (int h = 0; h < 24; h++) {
for (int m = 0; m < 60; m++) {
String hh = String.format("%02d", h);
String mm = String.format("%02d", m);
if ((time.charAt(0) == '?' || time.charAt(0) == hh.charAt(0)) &&
(time.charAt(1) == '?' || time.charAt(1) == hh.charAt(1)) &&
(time.charAt(3) == '?' || time.charAt(3) == mm.charAt(0)) &&
(time.charAt(4) == '?' || time.charAt(4) == mm.charAt(1))) {
count++;
}
}
}
return count;
}
public static void main(String[] args) {
String time = "?5:00";
System.out.println(validClockTimes(time)); // Outputs: 2
}
}#include <iostream>
#include <string>
int validClockTimes(const std::string& time) {
int count = 0;
for (int h = 0; h < 24; ++h) {
for (int m = 0; m < 60; ++m) {
std::string hh = (h < 10 ? "0" : "") + std::to_string(h);
std::string mm = (m < 10 ? "0" : "") + std::to_string(m);
if ((time[0] == '?' || time[0] == hh[0]) &&
(time[1] == '?' || time[1] == hh[1]) &&
(time[3] == '?' || time[3] == mm[0]) &&
(time[4] == '?' || time[4] == mm[1])) {
++count;
}
}
}
return count;
}
int main() {
std::string time = "?5:00";
std::cout << validClockTimes(time) << std::endl; // Outputs: 2
return 0;
}function validClockTimes(time) {
let count = 0;
for (let h = 0; h < 24; h++) {
for (let m = 0; m < 60; m++) {
let hh = h.toString().padStart(2, '0');
let mm = m.toString().padStart(2, '0');
if ((time[0] === '?' || time[0] === hh[0]) &&
(time[1] === '?' || time[1] === hh[1]) &&
(time[3] === '?' || time[3] === mm[0]) &&
(time[4] === '?' || time[4] === mm[1])) {
count++;
}
}
}
return count;
}
console.log(validClockTimes('?5:00')); // Outputs: 2#include <stdio.h>
int validClockTimes(char* time) {
int count = 0;
for (int h = 0; h < 24; h++) {
for (int m = 0; m < 60; m++) {
char hh[3], mm[3];
snprintf(hh, sizeof(hh), "%02d", h);
snprintf(mm, sizeof(mm), "%02d", m);
if ((time[0] == '?' || time[0] == hh[0]) &&
(time[1] == '?' || time[1] == hh[1]) &&
(time[3] == '?' || time[3] == mm[0]) &&
(time[4] == '?' || time[4] == mm[1])) {
count++;
}
}
}
return count;
}
int main() {
char time[] = "?5:00";
printf("%d\n", validClockTimes(time)); // Outputs: 2
return 0;
}using System;
public class ValidClockTimes {
public static int ValidTimes(string time) {
int count = 0;
for (int h = 0; h < 24; h++) {
for (int m = 0; m < 60; m++) {
string hh = h.ToString("D2");
string mm = m.ToString("D2");
if ((time[0] == '?' || time[0] == hh[0]) &&
(time[1] == '?' || time[1] == hh[1]) &&
(time[3] == '?' || time[3] == mm[0]) &&
(time[4] == '?' || time[4] == mm[1])) {
count++;
}
}
}
return count;
}
public static void Main() {
string time = "?5:00";
Console.WriteLine(ValidTimes(time)); // Outputs: 2
}
}This Python solution iterates through all potential hours (0 through 23) and minutes (0 through 59). For each hour-minute combination, it formats them into strings 'hh' and 'mm'. It then checks if each character matches the corresponding character in the given time string or if the character is '?', which can match any digit. If all positions match or are '?', this configuration of time is considered valid, and the count is incremented.
The time complexity is O(1) since there are at most 24*60 = 1440 iterations. The space complexity is O(1) as we use only a few variables to store numbers and strings.
Approach 2: Character-Specific Enumeration
This approach simplifies the task by considering each position of '?' in the string individually, providing specific potential values given constraints (e.g., for 'hh', values depend on `time[0]`).
def valid_clock_times_optimized(time: str) -> int:
total_ways = 1
if time[0] == '?':
total_ways *= 3 if time[1] == '?' or time[1] <= '3' else 2
if time[1] == '?':
total_ways *= 10 if time[0] in ['0', '1'] else 4
if time[3] == '?':
total_ways *= 6
if time[4] == '?':
total_ways *= 10
return total_ways
time = "?5:00"
print(valid_clock_times_optimized(time)) # Outputs: 2public class ValidClockTimesOptimized {
public static int validClockTimesOptimized(String time) {
int totalWays = 1;
if (time.charAt(0) == '?') {
totalWays *= (time.charAt(1) == '?' || time.charAt(1) <= '3') ? 3 : 2;
}
if (time.charAt(1) == '?') {
totalWays *= (time.charAt(0) == '0' || time.charAt(0) == '1') ? 10 : 4;
}
if (time.charAt(3) == '?') {
totalWays *= 6;
}
if (time.charAt(4) == '?') {
totalWays *= 10;
}
return totalWays;
}
public static void main(String[] args) {
String time = "?5:00";
System.out.println(validClockTimesOptimized(time)); // Outputs: 2
}
}#include <iostream>
int validClockTimesOptimized(std::string time) {
int totalWays = 1;
if (time[0] == '?') {
totalWays *= (time[1] == '?' || time[1] <= '3') ? 3 : 2;
}
if (time[1] == '?') {
totalWays *= (time[0] == '0' || time[0] == '1') ? 10 : 4;
}
if (time[3] == '?') {
totalWays *= 6;
}
if (time[4] == '?') {
totalWays *= 10;
}
return totalWays;
}
int main() {
std::string time = "?5:00";
std::cout << validClockTimesOptimized(time) << std::endl; // Outputs: 2
return 0;
}function validClockTimesOptimized(time) {
let totalWays = 1;
if (time[0] === '?') {
totalWays *= (time[1] === '?' || time[1] <= '3') ? 3 : 2;
}
if (time[1] === '?') {
totalWays *= (time[0] === '0' || time[0] === '1') ? 10 : 4;
}
if (time[3] === '?') {
totalWays *= 6;
}
if (time[4] === '?') {
totalWays *= 10;
}
return totalWays;
}
console.log(validClockTimesOptimized('?5:00')); // Outputs: 2#include <stdio.h>
int validClockTimesOptimized(char* time) {
int totalWays = 1;
if (time[0] == '?') {
totalWays *= (time[1] == '?' || time[1] <= '3') ? 3 : 2;
}
if (time[1] == '?') {
totalWays *= (time[0] == '0' || time[0] == '1') ? 10 : 4;
}
if (time[3] == '?') {
totalWays *= 6;
}
if (time[4] == '?') {
totalWays *= 10;
}
return totalWays;
}
int main() {
char time[] = "?5:00";
printf("%d\n", validClockTimesOptimized(time)); // Outputs: 2
return 0;
}using System;
public class ValidClockTimesOptimized {
public static int ValidClockTimesOptimized(string time) {
int totalWays = 1;
if (time[0] == '?') {
totalWays *= (time[1] == '?' || time[1] <= '3') ? 3 : 2;
}
if (time[1] == '?') {
totalWays *= (time[0] == '0' || time[0] == '1') ? 10 : 4;
}
if (time[3] == '?') {
totalWays *= 6;
}
if (time[4] == '?') {
totalWays *= 10;
}
return totalWays;
}
public static void Main() {
string time = "?5:00";
Console.WriteLine(ValidClockTimesOptimized(time)); // Outputs: 2
}
}The Python optimized solution calculates the number of valid replacements by checking each character in 'time'. Depending on whether a character is '?', it multiplies the total possible number of ways by the valid number of digits appropriate for that character.
Time Complexity: O(1), due to the constant number of checks and multiplicative operations. Space Complexity: O(1) as only a few integer calculations are involved.
Approach 3: Enumeration
We can directly enumerate all times from 00:00 to 23:59, then judge whether each time is valid, if so, increment the answer.
After the enumeration ends, return the answer.
The time complexity is O(24 times 60), and the space complexity is O(1).
function countTime(time: string): number {
let ans = 0;
for (let h = 0; h < 24; ++h) {
for (let m = 0; m < 60; ++m) {
const s = `${h}`.padStart(2, '0') + ':' + `${m}`.padStart(2, '0');
let ok = 1;
for (let i = 0; i < 5; ++i) {
if (s[i] !== time[i] && time[i] !== '?') {
ok = 0;
break;
}
}
ans += ok;
}
}
return ans;
}func countTime(time string) int {
ans := 0
for h := 0; h < 24; h++ {
for m := 0; m < 60; m++ {
s := fmt.Sprintf("%02d:%02d", h, m)
ok := 1
for i := 0; i < 5; i++ {
if s[i] != time[i] && time[i] != '?' {
ok = 0
break
}
}
ans += ok
}
}
return ans
}impl Solution {
pub fn count_time(time: String) -> i32 {
let mut ans = 0;
for i in 0..24 {
for j in 0..60 {
let mut ok = true;
let t = format!("{:02}:{:02}", i, j);
for (k, ch) in time.chars().enumerate() {
if ch != '?' && ch != t.chars().nth(k).unwrap() {
ok = false;
}
}
if ok {
ans += 1;
}
}
}
ans
}
}Approach 4: Optimized Enumeration
We can separately enumerate hours and minutes, count how many hours and minutes meet the condition, and then multiply them together.
The time complexity is O(24 + 60), and the space complexity is O(1).
function countTime(time: string): number {
const f = (s: string, m: number): number => {
let cnt = 0;
for (let i = 0; i < m; ++i) {
const a = s[0] === '?' || s[0] === Math.floor(i / 10).toString();
const b = s[1] === '?' || s[1] === (i % 10).toString();
if (a && b) {
++cnt;
}
}
return cnt;
};
return f(time.slice(0, 2), 24) * f(time.slice(3), 60);
}func countTime(time string) int {
f := func(s string, m int) (cnt int) {
for i := 0; i < m; i++ {
a := s[0] == '?' || int(s[0]-'0') == i/10
b := s[1] == '?' || int(s[1]-'0') == i%10
if a && b {
cnt++
}
}
return
}
return f(time[:2], 24) * f(time[3:], 60)
}impl Solution {
pub fn count_time(time: String) -> i32 {
let f = |s: &str, m: usize| -> i32 {
let mut cnt = 0;
let first = s.chars().nth(0).unwrap();
let second = s.chars().nth(1).unwrap();
for i in 0..m {
let a = first == '?' || (first.to_digit(10).unwrap() as usize) == i / 10;
let b = second == '?' || (second.to_digit(10).unwrap() as usize) == i % 10;
if a && b {
cnt += 1;
}
}
cnt
};
f(&time[..2], 24) * f(&time[3..], 60)
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| Brute Force Enumeration | The time complexity is O(1) since there are at most 24*60 = 1440 iterations. The space complexity is O(1) as we use only a few variables to store numbers and strings. |
| Character-Specific Enumeration | Time Complexity: O(1), due to the constant number of checks and multiplicative operations. Space Complexity: O(1) as only a few integer calculations are involved. |
| Enumeration | – |
| Optimized Enumeration | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force Enumeration | O(1440) | O(1) | When you want the simplest implementation or to quickly validate the pattern against all valid times |
| Character-Specific Enumeration | O(1) | O(1) | Preferred solution in interviews; directly counts valid combinations using clock constraints |
Frequently asked questions
Is Number of Valid Clock Times easy or hard?
LeetCode classifies Number of Valid Clock Times as an Easy problem. The brute force solution is straightforward, while the optimized solution requires reasoning about valid hour and minute digit ranges in a 24‑hour clock.
Number of Valid Clock Times Python/Java solution
Both Python and Java implementations usually follow either brute force enumeration of all 1440 times or the optimized counting approach. The counting method checks each position of the string (h1, h2, m1, m2) and calculates how many digits are possible when a '?' appears.
How to solve Number of Valid Clock Times in O(1)?
Compute valid combinations separately for hours and minutes. Minutes allow 00–59, so the first digit has 0–5 options and the second 0–9 depending on '?'. Hours allow 00–23, so the valid digits depend on whether the first digit is 0, 1, or 2. Multiply the number of valid hour and minute possibilities to get the final count in constant time.
What is the best approach for Number of Valid Clock Times?
The best approach is character-specific enumeration. Instead of checking all 1440 possible times, analyze each digit position in the "hh:mm" format and count how many valid digits can replace each '?'. Multiply the valid hour combinations by the valid minute combinations. This runs in O(1) time and O(1) space.
Is Number of Valid Clock Times asked at Google/Amazon/Meta?
String enumeration and constraint-based counting problems like this appear in interviews at large tech companies including Amazon, Google, and Meta. They are typically used in early interview rounds to test reasoning about constraints and clean implementation.
What data structure is used in Number of Valid Clock Times?
The problem mainly uses string processing and enumeration. No complex data structures are required. Solutions typically iterate through characters of the time string and apply conditional logic to count valid digit combinations.
What is the time complexity of Number of Valid Clock Times?
Two common solutions exist. Brute force enumeration checks all 24 × 60 possible times, resulting in O(1440) time and O(1) space. The optimized counting approach computes possibilities for each digit directly, giving O(1) time and O(1) space complexity.
