Binary Watch

Enumerate all hh:mm times whose binary representations have exactly `turnedOn` LEDs.

Easy
Time O(1) Space O(1)
LeetCode
3 min read
backtracking bit-manipulation

Problem#

A binary watch has 4 LEDs for hours (0–11) and 6 LEDs for minutes (0–59). Return all times such that the total set bits equals turnedOn.

Examples#

  • turnedOn = 1["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"]

Constraints#

  • 0 <= turnedOn <= 10.

Approach#

Bounded enumeration: hours 0–11, minutes 0–59. Compare combined popcount.

Solution#

Binary Watch
class Solution {
public:
vector<string> readBinaryWatch(int turnedOn) {
vector<string> out;
for (int h = 0; h < 12; ++h)
for (int m = 0; m < 60; ++m)
if (__builtin_popcount(h) + __builtin_popcount(m) == turnedOn)
out.push_back(to_string(h) + ":" + (m < 10 ? "0" : "") + to_string(m));
return out;
}
};

Editorial#

Total search space is 720 entries — direct enumeration beats any clever bitmask partitioning. __builtin_popcount is a single hardware instruction on most platforms.

Complexity#

  • Time: O(1) (bounded).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.