Problem 401

Abstract / Summary

A binary watch uses LEDs to show hours and minutes find how many times the LEDs light up to show all valid times.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0401.py

class Solution:
    def readBinaryWatch(self, turnedOn: int) -> List[str]:
        # just brute-force it, no smart bit rearrangement
        for hour in range(12):
            for minute in range(60):
                if hour.bit_count() + minute.bit_count() == turnedOn:
                    yield f"{hour}:{minute:02d}"
7 lines | 327 bytes | submitted September 8, 2023 | GitHub   16% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 66% (400k+ submissions).

Typical patterns to solve this problem:
  • Backtracking
  • Bit Manipulation
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a single method readBinaryWatch. The method receives an integer turnedOn that represents the number of LEDs illuminated on a binary watch. It enumerates every possible hour-minute combination, checks whether the total number of set bits matches turnedOn, and yields the formatted time strings that satisfy the condition. The use of a generator makes the result iterable without allocating a full collection up front.

Key Steps

The algorithm proceeds through three logical phases: iteration over hours, iteration over minutes, and bit-count validation followed by formatting.

Hour iteration

for hour in range(12):

The outer loop restricts hour to the valid range for a binary watch (0 through 11). By limiting the range to twelve values, the code eliminates any need for additional boundary checks later in the process.

Minute iteration

    for minute in range(60):

Nested inside the hour loop, this inner loop covers every minute from 0 to 59. The combination of the two loops yields exactly 720 distinct hour-minute pairs, which is the complete state space of a binary watch.

Bit-count validation

        if hour.bit_count() + minute.bit_count() == turnedOn:

For each pair, the built-in int.bit_count() method computes the number of 1-bits in the binary representation of hour and minute. The sum is compared to the target turnedOn. Because bit_count is implemented at the interpreter level, it runs faster than a manual loop that counts bits.

Formatting and yielding

            yield f"{hour}:{minute:02d}"

When the bit count matches, the method yields a string in the form H:MM. The minute component is zero-padded to two digits, ensuring that times such as 3:07 appear correctly, while the hour component is left without padding, matching the conventional display of binary watch times.

Edge Cases Handled

When turnedOn is zero, the only combination that satisfies the condition is 0:00. The loops still execute, the bit-count check succeeds for that single pair, and the generator yields the correctly formatted string.

If turnedOn exceeds the maximum possible number of illuminated LEDs (which is 10, because 4 bits represent hours and 6 bits represent minutes), the condition never becomes true, and the generator produces no output. This behavior gracefully handles out-of-range inputs without raising exceptions.

Minute values less than ten are automatically padded with a leading zero by the format specifier :02d, so times like 5:03 are emitted correctly. Hours from one to nine are emitted without a leading zero, preserving the expected H:MM layout.

The loops cover the full valid domain of hours and minutes, so there is no risk of missing a legitimate time or producing an invalid one.

Performance Optimizations

The most notable optimization is the reliance on the native int.bit_count() method. This operation is executed in compiled code and avoids the overhead of manual bit manipulation, delivering constant-time performance for each integer.

Using a generator (yield) instead of constructing a list means that memory consumption stays minimal regardless of how many matching times exist. Consumers can iterate over the results lazily, retrieving each formatted string only when needed.

The double loop iterates over a fixed, small search space (720 iterations). Because the bounds are hard-coded (range(12) and range(60)), the interpreter can optimize loop execution, and there is no dynamic allocation of auxiliary data structures during the search.

Overall, the combination of built-in bit counting, tight loop bounds, and lazy result production yields an implementation that is both concise and efficient for the problem domain.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a special watch that shows the time using tiny glowing lights. This piece of code is like a curious detective searching for every possible time that could be showing on the watch face.

It starts by looking at every single hour from zero to eleven. For each of those hours, it checks every single minute from zero to fifty-nine. To decide if a time is correct, the code counts how many lights are turned on for both the hour and the minute combined. If the total number of glowing lights matches the number given at the start, that time is found. When a matching time is discovered, the code writes it down in a perfect format with a colon in the middle and enough zeros to make sure the minutes look just right. It keeps doing this until every single hiding spot for the time has been checked.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.70 | σ = 1.70

Complexity Analysis

Time: constant
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Rust Python Go TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
linouk23 C++
lkwq007 Python
qiyuangong Java
ruoru Rust
suxrobGM C#
varunu28 Java
vli02 C
withaarzoo C++
yuanliu666 Kotlin
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
linouk23 C++
lkwq007 Python
qiyuangong Java
ruoru Rust
suxrobGM C#
varunu28 Java
vli02 C
withaarzoo C++
yuanliu666 Kotlin
zfang399 C++
38 links | 24 authors | 10 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

7 medium
8 solutions   September 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality