Binary Watch — LeetCode 401 Python Solution

EasyBit ManipulationBacktracking
Problem
#401
Reading time
2 min

The problem

A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom to represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right.

Example

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

Python solution

Python
class Solution:
    def readBinaryWatch(self, turnedOn: int) -> List[str]:
        return [
            '{:d}:{:02d}'.format(i, j)
            for i in range(12)
            for j in range(60)
            if (bin(i) + bin(j)).count('1') == turnedOn
        ]

Complexity

MeasureComplexity
TimeExponential (worst case)
SpaceO(depth) auxiliary

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 401. Binary Watch is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Backtracking.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 401. Binary Watch?
LeetCode 401. Binary Watch is rated Easy on LeetCode.
What topics does LeetCode 401. Binary Watch cover?
LeetCode 401. Binary Watch is tagged Bit Manipulation and Backtracking on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview