Binary Watch — LeetCode 401 Python Solution
- Problem
- #401
- Pattern
- Backtracking
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | Exponential (worst case) |
| Space | O(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.