Bulb Switcher II — LeetCode 672 Python Solution
- Problem
- #672
- Pattern
- Bit Manipulation
- Reading time
- 3 min
- Source
- leetcode.com
The problem
There is a room with n bulbs labeled from 1 to n that all are turned on initially, and four buttons on the wall. Each of the four buttons has a different functionality where: Button 1: Flips the status of all the bulbs.
Example
- Input
- n = 1, presses = 1
- Output
- 2
- Explanation
- Status can be:
Python solution
class Solution:
def flipLights(self, n: int, presses: int) -> int:
ops = (0b111111, 0b010101, 0b101010, 0b100100)
n = min(n, 6)
vis = set()
for mask in range(1 << 4):
cnt = mask.bit_count()
if cnt <= presses and cnt % 2 == presses % 2:
t = 0
for i, op in enumerate(ops):
if (mask >> i) & 1:
t ^= op
t &= (1 << 6) - 1
t >>= 6 - n
vis.add(t)
return len(vis)Complexity
| Measure | Complexity |
|---|---|
| Time | O(V+E) |
| Space | O(V) auxiliary |
Pattern: Bit Manipulation
Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 672. Bulb Switcher II is filed here because LeetCode tags it Bit Manipulation, which is the vocabulary this hub collects.
The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 672. Bulb Switcher II?
- LeetCode 672. Bulb Switcher II is rated Medium on LeetCode.
- What is the time complexity of LeetCode 672. Bulb Switcher II?
- The Python solution on this page runs in O(V+E).
- What is the space complexity of LeetCode 672. Bulb Switcher II?
- The Python solution on this page uses O(V) auxiliary space.
- What topics does LeetCode 672. Bulb Switcher II cover?
- LeetCode 672. Bulb Switcher II is tagged Bit Manipulation, Depth-First Search, Breadth-First Search and Math on LeetCode.