Count valid 24-hour times from four digits
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Microsoft. It tests enumeration, permutations and math.
Write a function count_valid_times(a, b, c, d) that takes four digits (each an integer from 0 to 9).
Arrange all four digits as HH:MM on a 24-hour clock, using each given digit exactly once. A time is valid when the hour is from 00 to 23 and the minute is from 00 to 59. Leading zeros are allowed.
Return the number of distinct valid times. If the digits repeat, two different arrangements may show the same time; count that time once.
Constraints
0 <= a, b, c, d <= 9
Example 1
Input: a = 1, b = 8, c = 3, d = 2
Output: 6
The valid times are 12:38, 13:28, 18:23, 18:32, 21:38 and 23:18.
Example 2
Input: a = 2, b = 3, c = 3, d = 2
Output: 3
The valid times are 22:33, 23:23 and 23:32. Several orderings of the digits produce each of these, but each time counts once.
Example 3
Input: a = 6, b = 2, c = 4, d = 7
Output: 0
Any hour that starts with 2 would be 24 or more, and there is no 0 or 1 to start an hour with.
Clarifying questions
- Must all four digits be used? (Yes: each exactly once.)
- Is
24:00a valid time? (No: the hour must be at most 23.) - Should the function return only the count, or also the times?
- Are the inputs always single digits, or should invalid values be rejected?
What a strong answer covers
- There are only 4! = 24 orderings. Generates them, forms the hour from the first two digits and the minute from the last two, checks both ranges, and stores valid
(hour, minute)pairs in a set so repeated digits count once. Constant time. - Names the alternative, looping over all 1,440 minutes of the day and comparing digit counts, and why either is fine at this size.
- Edge cases: repeated digits (Example 2), all zeros (only
00:00, so 1), all nines (0), and minutes with a leading zero. - Tests the three examples, plus a case with every digit the same.
Follow-ups
- Return the latest valid time as a string instead, or
""when there is none. - A 12-hour clock with AM/PM, or six digits with seconds.
-
ndigits and a general clock format: when does trying every permutation stop being reasonable?
Where it's asked
What it tests
enumeration · permutations · math
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
