Number of Valid Clock Times

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
    def countTime(self, time: str) -> int:
        ans = 1
        if time[4] == '?':
            ans = ans * 10
        if time[3] == '?':
            ans = ans * 6

        if time[0] == '?' and time[1] == '?':
            ans = ans * 24
        else:
            if time[1] == '?':
                if time[0] == '2':
                    ans = ans * 4
                else:
                    ans = ans * 10
            if time[0] == '?':
                if time[1] < '4':
                    ans = ans * 3
                else:
                    ans = ans * 2
        return ans

In this Python code, ans is initially set to 1. If the last character of the time string is ‘?’, ans is multiplied by 10. If the second last character is ‘?’, ans is multiplied by 6. These steps consider all possible minute combinations.

Next, it checks for hour combinations. If both hour characters are ‘?’, ans is multiplied by 24. Otherwise, if the first hour character is ‘?’, ans is multiplied by 3 if the second character is less than ‘4’, otherwise ans is multiplied by 2. If the second hour character is ‘?’, ans is multiplied by 4 if the first character is ‘2’, otherwise ans is multiplied by 10.

Finally, it returns ans, which is the total number of possible valid times.