Binary Watch (LeetCode 401): Solution and Explanation

Easy
Backtracking
Bit Manipulation

A watch shows the hour with 4 LEDs and the minute with 6 LEDs, each LED one bit. Given how many LEDs are on, list every time the watch could be showing.

Intuition

It is tempting to treat this as a backtracking problem: choose turnedOn of the 10 LEDs, then throw away choices that give an hour above 11 or a minute above 59.

Turn it around. There are only 12 hours and 60 minutes, so 720 times in total. For each time, the number of lit LEDs is just the number of 1 bits in the hour plus the number of 1 bits in the minute.

So loop over every hour and minute, count bits, and keep the times whose count equals turnedOn. Invalid times never appear, because the loops only produce valid ones.

Approach: Enumerate every time and count bits

  1. Start with an empty result list.
  2. For each hour h from 0 to 11 and each minute m from 0 to 59, compute popcount(h) + popcount(m).
  3. If it equals turnedOn, append the time as h:mm, with no leading zero on the hour and two digits for the minute.
  4. Return the list.

Step-by-step example

turnedOn = 1
  1. Hour 0 is 0000 and uses no LEDs, so the minute must light exactly one: minutes 1, 2, 4, 8, 16 and 32. Add 0:01, 0:02, 0:04, 0:08, 0:16, 0:32.
  2. Hour 1 is 0001 and uses one LED, so the minute must be 0. Add 1:00.
  3. Hour 2 (0010), hour 4 (0100) and hour 8 (1000) each use one LED too, so add 2:00, 4:00 and 8:00.
  4. Every other hour has two or more bits set and is already over budget.
  5. Return the 10 times: ["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"].

Code: Python, Java, C++

1class Solution:
2    def readBinaryWatch(self, turnedOn: int) -> List[str]:
3        result = []
4        for h in range(12):
5            for m in range(60):
6                if bin(h).count('1') + bin(m).count('1') == turnedOn:
7                    result.append(f"{h}:{m:02d}")
8        return result
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(1)

The loops always run 12 x 60 = 720 times, and counting bits in a number below 64 takes constant time.

Space

O(1)

Apart from the output list, only the loop counters are stored. The output holds at most 190 times (turnedOn = 4 or 5 gives the most).

Other approaches

Backtracking over the 10 LEDs (time O(C(10, turnedOn)), space O(10))

Choose turnedOn LEDs out of 10 recursively, build the hour from the first four and the minute from the last six, and keep the combination if the hour is at most 11 and the minute at most 59.

Precompute minutes by bit count (time O(1), space O(1))

Group the 60 minutes by their bit count once. For each hour, look up the group for turnedOn - popcount(h) and append those minutes directly.

Common mistakes

  • Padding the hour. The hour is written without a leading zero, so 1:00 is right and 01:00 is wrong.
  • Forgetting to pad the minute. 10:02 is right and 10:2 is wrong.
  • Letting the hour reach 12 or the minute reach 60. With backtracking over LEDs, combinations such as 1100 for the hour must be rejected; the double loop never produces them.
  • Assuming large turnedOn always has answers. An hour uses at most 3 LEDs (11) and a minute at most 5 (59), so 9 or 10 LEDs give an empty list.

Frequently asked questions

Why is this in the backtracking category if a double loop solves it?

The problem is often taught as choosing which LEDs to turn on, which is a combinations search. The double loop is simpler and just as fast because the space of valid times is tiny.

Does the order of the output matter?

No. Any order is accepted. Looping hours then minutes naturally produces the times in increasing order.

How do I count 1 bits in each language?

Python has bin(x).count('1'), Java has Integer.bitCount, C++ has __builtin_popcount. In other languages a short loop that clears the lowest set bit with x & (x - 1) works.

What is the largest number of LEDs that can be on?

Eight: hour 11 (1011) uses three and minute 59 (111011) uses five. Inputs of 9 or 10 return an empty list.