Leetcode #672: Bulb Switcher II
In this guide, we solve Leetcode #672 Bulb Switcher II in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Bit Manipulation, Depth-First Search, Breadth-First Search, Math
Intuition
We need to explore a structure deeply before backing up, which suits DFS.
DFS keeps local context on the call stack and is easy to implement recursively.
Approach
Define a recursive DFS that carries the necessary state.
Combine child results as the recursion unwinds.
Steps:
- Define a recursive DFS with state.
- Visit children and combine results.
- Return the final aggregation.
Example
Input: n = 1, presses = 1
Output: 2
Explanation: Status can be:
- [off] by pressing button 1
- [on] by pressing button 2
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
The time complexity is O(V+E). The space complexity is O(V).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.