⌚ Beginner-Friendly Guide 'Binary Watch' - Problem 401 (C++, Python, JavaScript)
Source: Dev.to

Problem Summary
You’re given:
An integer turnedOn, which represents the total number of LEDs currently glowing on a binary watch.
Your goal:
Return a list of all possible valid times the watch could be showing. Hours must be between 0 and 11, and minutes between 0 and 59.
Intuition
The watch has 10 LEDs in total: 4 for hours and 6 for minutes. Since the total number of possible times is small (only 2¹⁰ = 1024 combinations), a backtracking (DFS) approach works well.
The algorithm iterates through the 10 LEDs. For each LED we decide to turn it on, decrement turnedOn, and update the current hour or minute value, making sure we never exceed the limits (hour 8, no valid time exists.
Result: [] (empty list).
C++ Solution
class Solution {
public:
vector readBinaryWatch(int turnedOn) {
vector ans;
// Start DFS with turnedOn LEDs remaining, starting at index 0, hour 0, minute 0
dfs(turnedOn, 0, 0, 0, ans);
return ans;
}
private:
const int hours[4] = {1, 2, 4, 8};
const int minutes[6] = {1, 2, 4, 8, 16, 32};
void dfs(int turnedOn, int s, int h, int m, vector& ans) {
if (turnedOn == 0) {
string time = to_string(h) + ":" + (m
Python Solution
List[str]:
ans = []
hours = [1, 2, 4, 8]
minutes = [1, 2, 4, 8, 16, 32]
def dfs(remaining, start_idx, h, m):
if remaining == 0:
ans.append(f"{h}:{m:02d}")
return
for i in range(start_idx, 10):
if i
JavaScript Solution
{
if (remaining === 0) {
const formattedMin = m < 10 ? "0" + m : m;
ans.push(h + ":" + formattedMin);
return;
}
for (let i = startIdx; i < 10; i++) {
if (i < 4) { // Hour LEDs
if (h + hours[i] < 12) {
dfs(remaining - 1, i + 1, h + hours[i], m);
}
} else { // Minute LEDs
if (m + minutes[i - 4] < 60) {
dfs(remaining - 1, i + 1, h, m + minutes[i - 4]);
}
}
}
};
dfs(turnedOn, 0, 0, 0);
return ans;
};
Key Takeaways
- Combinatorial Search: Backtracking efficiently explores all LED combinations that satisfy a fixed count.
- State Management: Passing
h(hours) andm(minutes) through recursion keeps the watch state without needing explicit undo steps. - Constraint Checking: Validating boundaries (
hours < 12,minutes < 60) before recursing prunes invalid paths early, saving computation.
Final Thoughts
This problem illustrates the interplay between hardware representation (bits) and software logic. While conceptually simple, it tests handling multiple constraints and proper formatting. Similar bit‑manipulation and combinatorial techniques appear in embedded systems, driver development, and network protocol design where every bit counts.