Number of Valid Clock Times - Problem

You are given a string time of length 5 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.

Input & Output

Example 1 — Single Unknown Digits
$ Input: time = "?4:5?"
Output: 20
💡 Note: First digit can be 0, 1, or 2 (since 34:5X would be invalid). Last digit can be 0-9. Total: 2 valid first digits × 10 last digits = 20 combinations.
Example 2 — Multiple Unknown Positions
$ Input: time = "0?:??"
Output: 600
💡 Note: First hour digit is 0, second can be 0-9 (10 choices). Minutes can be 00-59 (60 choices). Total: 10 × 60 = 600.
Example 3 — All Digits Known
$ Input: time = "12:34"
Output: 1
💡 Note: No question marks, so only one valid time: 12:34 itself.

Constraints

  • time.length == 5
  • time is in the format "hh:mm"
  • Each character is either a digit or '?'

Visualization

Tap to expand
Number of Valid Clock Times INPUT ?4:5? Time String Analysis ? h1 4 h2 : sep 5 m1 ? m2 Unknown (?) Known digit Hours: 00-23 | Minutes: 00-59 time = "?4:5?" Input: time = "?4:5?" ALGORITHM STEPS 1 Count h1 options h2=4, so h1 can be 0,1,2 = 3 2 Count h2 options h2=4 (fixed, not ?) = 1 3 Count m1 options m1=5 (fixed, not ?) = 1 4 Count m2 options m2=?, can be 0-9 = 10 Multiply all counts: 3 x 1 x 1 x 10 = 20 FINAL RESULT Answer 20 Sample Valid Times: 04:50 14:51 24:52 04:53 14:57 24:59 Breakdown: h1: 0,1,2 (3 options) h2: 4 (fixed) m1: 5 (fixed) m2: 0-9 (10 options) Key Insight: Each position in the time string can be analyzed independently. For hours (hh), if h1 is ?, it depends on h2's value: h1 can be 0-2 if h2 is 0-3, or 0-1 if h2 is 4-9. For minutes, m1 can be 0-5 and m2 can be 0-9. The total count is the product of all individual position possibilities. Time complexity: O(1). TutorialsPoint - Number of Valid Clock Times | Conditional Counting Approach
Asked in
Google 15 Facebook 12 Amazon 8
23.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen