A binary watch shows the time with ten LEDs. Four of them give the hour (worth 8, 4, 2 and 1) and six give the minutes (worth 32, 16, 8, 4, 2 and 1). The hour is the sum of its lit LEDs, and so is the minute.
You are told only how many LEDs are lit, turnedOn. Return every time the watch could be showing, in any order. A real time has an hour from 0 to 11 and a minute from 0 to 59.
Write each time as hour, colon, minute. The hour has no leading zero (3:07, not 03:07) and the minute always has two digits (3:07, not 3:7).
Example 1
Input: turnedOn = 8 Output: ["7:31","7:47","7:55","7:59","11:31","11:47","11:55","11:59"] Why: only 7 and 11 use 3 hour LEDs, and only these minutes use 5
2 more examples and the constraints
Example 2
Input: turnedOn = 0 Output: ["0:00"] Why: with every LED off the watch reads midnight
Example 3
Input: turnedOn = 10 Output: [] Why: all four hour LEDs make 15, which is past 11
Constraints
- 0 ≤ turnedOn ≤ 10
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Check every timeO(1) · 720 checks
- Light the LEDs one by oneO(C(10, k))
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Checks in the worst case (turnedOn = 5) | Verdict |
|---|---|---|---|
| Check every time | O(1) · 720 | Simplest; always 720 checks | |
| Light the LEDs one by one | O(C(10, k)) | Best; only builds real choices |
k = turnedOn. Both are constant time because the watch never changes size; C(10, 5) = 252 is the largest number of LED choices.
Edge cases to test
- No LEDs lit. The only time is 0:00.
- Too many LEDs. At most 3 hour LEDs (7 or 11) and 5 minute LEDs (31, 47, 55, 59) can be lit, so 9 or 10 gives an empty list.
- Small minutes. Minute 5 prints as
:05; forgetting the zero gives3:5. - Hours that look valid. 8 + 4 = 12 uses two LEDs but is not an hour on this watch.
Common mistakes
- Padding the hour with a zero, giving
03:07instead of3:07. - Allowing hour 12 to 15 or minute 60 to 63, which the LEDs can show but a watch cannot.
- In the backtracking, starting each loop at 0 instead of i + 1, which adds the same time many times.
How to talk through it
- 1Clarify. Which hours and minutes are real? Any output order? How should times be formatted?
- 2See the bits. The lit LEDs are just the 1 bits of the hour and the minute.
- 3Offer the simple loop. 720 times, two bit counts each: constant time and easy to trust.
- 4Mention the backtracking. Choosing which LEDs are lit, with pruning past 11 or 59, builds only real choices.
- 5Test out loud. Run 0 (only 0:00), 1 (ten times), and 9 (no times at all).
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?