Binary Watch
Enumerate all hh:mm times whose binary representations have exactly `turnedOn` LEDs.
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#
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; }};func readBinaryWatch(turnedOn int) []string { out := []string{} for h := 0; h < 12; h++ { for m := 0; m < 60; m++ { if bits.OnesCount(uint(h))+bits.OnesCount(uint(m)) == turnedOn { out = append(out, fmt.Sprintf("%d:%02d", h, m)) } } } return out}from typing import List
class Solution: def readBinaryWatch(self, turnedOn: int) -> List[str]: out: List[str] = [] for h in range(12): for m in range(60): if bin(h).count('1') + bin(m).count('1') == turnedOn: out.append(f"{h}:{m:02d}") return outvar readBinaryWatch = function(turnedOn) { const popcount = (x) => { let c = 0; while (x) { c += x & 1; x >>>= 1; } return c; }; const out = []; for (let h = 0; h < 12; h++) { for (let m = 0; m < 60; m++) { if (popcount(h) + popcount(m) === turnedOn) { out.push(`${h}:${m < 10 ? '0' : ''}${m}`); } } } return out;};class Solution { public List<String> readBinaryWatch(int turnedOn) { List<String> out = new ArrayList<>(); for (int h = 0; h < 12; h++) { for (int m = 0; m < 60; m++) { if (Integer.bitCount(h) + Integer.bitCount(m) == turnedOn) { out.add(String.format("%d:%02d", h, m)); } } } return out; }}function readBinaryWatch(turnedOn: number): string[] { const popcount = (x: number): number => { let c = 0; while (x) { c += x & 1; x >>>= 1; } return c; }; const out: string[] = []; for (let h = 0; h < 12; h++) { for (let m = 0; m < 60; m++) { if (popcount(h) + popcount(m) === turnedOn) { out.push(`${h}:${m < 10 ? '0' : ''}${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#
Related#