MediumNo. 0672

Bulb Switcher II — LeetCode 672 Python Solution

Topics
Bit Manipulation, Depth-First Search, Breadth-First Search, Math
Reading time
3 min

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

PythonSolution
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

Time
O(V+E)
Space · auxiliary
O(V)

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

Related problems
No.ProblemDifficulty
0319Bulb SwitcherMedium
0365Water and Jug ProblemMedium
1457Pseudo-Palindromic Paths in a Binary TreeMedium
0662Maximum Width of Binary TreeMedium
0100Same TreeEasy
0101Symmetric TreeEasy

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.

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.

Free to download. Check it runs on your machine, then pick a plan.