#401
Binary Watch
EasyBacktrackingBit ManipulationBacktrackingBit Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(1) | O(1) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(1)Space O(n)
The optimal solution leverages backtracking to generate combinations of hours and minutes based on the number of LEDs turned on. This reduces the number of unnecessary checks and directly builds valid times.
⚙️
Algorithm
4 steps- 1Step 1: Use a backtracking function that takes the current hour, minute, and the number of LEDs turned on.
- 2Step 2: If the number of LEDs used exceeds 'turnedOn', return.
- 3Step 3: If the hour is valid (0-11) and the minute is valid (0-59), check if the total LEDs used equals 'turnedOn' and add the formatted time to the result.
- 4Step 4: Recursively try adding LEDs to the hour and minute, incrementing the count of LEDs used.
solution.py17 lines
1# Full working Python code
2from typing import List
3
4def readBinaryWatch(turnedOn: int) -> List[str]:
5 result = []
6 def backtrack(hour, minute, count):
7 if count > turnedOn:
8 return
9 if hour < 12 and minute < 60:
10 if count == turnedOn:
11 result.append(f'{hour}:{minute:02}')
12 if hour < 12:
13 backtrack(hour + 1, minute, count + bin(hour).count('1'))
14 if minute < 60:
15 backtrack(hour, minute + 1, count + bin(minute).count('1'))
16 backtrack(0, 0, 0)
17 return resultℹ
Complexity note: The time complexity remains O(1) since we are still limited by the fixed number of hours and minutes. The space complexity is O(n) due to the result list.
- 1Understanding how to represent time in binary is crucial.
- 2Efficiently counting bits can significantly reduce unnecessary computations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.