algoadvance

Leetcode 2437. Number of Valid Clock Times

Problem Statement

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).

Clarifying Questions

  1. Range of the String: Are we guaranteed that the input string is always in the format “HH:MM”?
    • Assumption: Yes, the string is always in the correct format.
  2. Character Constraints: Are the positions of the ‘?’ fixed, and can they appear in any position?
    • Assumption: ‘?’ can appear in any of the positions, including multiple ones.
  3. Valid Times: Should we consider leading zeros in valid times (e.g., 00:00 to 09:59)?
    • Assumption: Yes, leading zeros are valid in a 24-hour time format.

Strategy

To solve the problem, we’ll take the following approach:

  1. Identify Positions of ‘?’: For each position in the “HH:MM” format, determine the valid digits that can replace ‘?’.
  2. Count Valid Combinations: Multiply the number of valid choices for each position to get the total valid times.

Here’s a step-by-step breakdown for each position in the string “HH:MM”:

Code

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;
}

Time Complexity

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.

Explanation

This code examines each position in the given time string and determines how many valid digits can replace the ‘?’ character:

Multiplying the number of choices for each position gives the total count of valid times.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI