LeetCode 2437. Number of Valid Clock Times Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
2437. Number of Valid Clock Times

Description

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:

  • time is a valid string of length 5 in 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 from 0 to 9.

Solutions

Solution 1: 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 × 60), and the space complexity is O(1).

PythonJavaC++GoTypeScriptRust
class Solution: def countTime(self, time: str) -> int: def check(s: str, t: str) -> bool: return all(a == b or b == '?' for a, b in zip(s, t)) return sum( check(f'{h:02d}:{m:02d}', time) for h in range(24) for m in range(60) )(code-box)

Solution 2: 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).

PythonJavaC++GoTypeScriptRust
class Solution: def countTime(self, time: str) -> int: def f(s: str, m: int) -> int: cnt = 0 for i in range(m): a = s[0] == '?' or (int(s[0]) == i // 10) b = s[1] == '?' or (int(s[1]) == i % 10) cnt += a and b return cnt return f(time[:2], 24) * f(time[3:], 60)(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !