Problem 672

Abstract / Summary

Given a room with n bulbs and k people flipping bulbs in turns, determine how many bulbs remain on after all people have finished.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0672.py

class Solution:
    def flipLights(self, n: int, presses: int) -> int:
        one   = sum(1 << i for i in range(n))
        two   = sum(1 << i for i in range(1, n, 2))
        three = sum(1 << i for i in range(0, n, 2))
        four  = sum(1 << i for i in range(0, n, 3))

        todo = set([ one ])
        for i in range(presses):
            next = set()
            for t in todo:
                next.add(t ^ one)
                next.add(t ^ two)
                next.add(t ^ three)
                next.add(t ^ four)
            todo = next

        return len(todo)
18 lines | 594 bytes | submitted October 22, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 50% (60k+ submissions).

Typical patterns to solve this problem:
  • Bit Manipulation
  • Breadth First Search
  • Depth First Search
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The implementation solves the “flip lights” combinatorial problem by representing the on/off state of each light as a single bit in an integer. Each possible button press corresponds to a pre-computed bit mask that flips a specific subset of lights. By repeatedly applying XOR between the current state and each mask, the algorithm enumerates every reachable configuration after a given number of presses. The final answer is the count of distinct configurations stored in a set.

Key Steps

Bit-mask construction

Four masks are built once, before any press simulation. The first mask flips every light, the second flips lights at odd indices, the third flips lights at even indices, and the fourth flips lights whose index is a multiple of three. Each mask is created by summing left-shifted 1 values for the appropriate indices.

one   = sum(1 << i for i in range(n))          # all lights
two   = sum(1 << i for i in range(1, n, 2))   # odd positions
three = sum(1 << i for i in range(0, n, 2))   # even positions
four  = sum(1 << i for i in range(0, n, 3))   # positions divisible by 3

Initial state set

The algorithm starts with a set containing only the state produced by applying the “all-lights” mask once. This choice works because the set will be expanded by XORing with all masks in the next step, effectively covering the empty-press scenario as well.

todo = set([one])

Iterative press simulation

For each allowed press, a new temporary set is built. Every state currently in todo is XOR-ed with each of the four masks, generating the four possible outcomes of a single additional button press. The temporary set automatically discards duplicate states, ensuring that only unique configurations survive to the next iteration.

for i in range(presses):
    next = set()
    for t in todo:
        next.add(t ^ one)
        next.add(t ^ two)
        next.add(t ^ three)
        next.add(t ^ four)
    todo = next

Result extraction

After processing the required number of presses, the size of the todo set directly yields the number of distinct light configurations reachable.

return len(todo)

Edge Cases Handled

When the number of lights n is zero, each mask evaluates to 0 because the generator expressions produce no elements. The initial set therefore contains a single state 0. Subsequent XOR operations with a mask of 0 leave the state unchanged, so the algorithm correctly returns 1, indicating only the empty configuration is possible.

If the number of allowed presses presses is zero, the outer loop does not execute. The set todo still holds the single state created from the “all-lights” mask, and the function returns 1, reflecting that no toggling occurs and only the initial configuration exists.

When presses exceeds the number of distinct reachable configurations (which is bounded by the combination of the four masks), the set quickly stabilizes. The use of a Python set guarantees that once all possible states have been generated, further iterations simply re-add the same elements, leaving the set size unchanged. This implicit convergence prevents unnecessary growth of the state space.

Performance Optimizations

The code leverages integer bit operations instead of array or string representations, allowing each light configuration to be stored and manipulated in constant time per operation. Pre-computing the four masks eliminates repeated calculation of which lights each button affects, reducing overhead inside the nested loops.

Using XOR (^) to apply a mask is both fast and expressive: it flips exactly the bits indicated by the mask without needing conditional logic. The set data structure automatically handles deduplication, so the algorithm does not waste effort revisiting identical configurations. Because the number of unique states is limited by the four masks, the inner loop processes at most a small constant number of elements regardless of the values of n and presses, leading to efficient execution even for large inputs.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long row of little light bulbs in your room. Some are turned on and some are turned off. You have four magic buttons that you can press to change how the lights look.

The first button is very special because it flips every single light. If a light was off, it turns on, and if it was on, it turns off. The second button only touches the lights in the even spots, like the second, fourth, and sixth ones. The third button does the same thing but for the odd spots like the first, third, and fifth ones. The fourth button is a bit different because it picks every third light to flip.

When you start, all the lights are glowing bright. You can choose to press any of these four buttons a certain number of times. Because you want to see all the different patterns you can make, you keep track of every unique way the lights can look after your presses. The computer acts like a helper who tries every single combination of button presses to see how many different blinking patterns are possible at the very end. By keeping all these patterns in a group, the computer makes sure it does not count the same look twice. It is like collecting cards where you only care about finding every different type that exists.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 6 | μ = 6.04 | σ = 1.89

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Go Python
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
gouthampradhan Java
JoshCrozier JS
ruoru Rust
suxrobGM C#
wisdompeak C++
yuanliu666 Kotlin
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
gouthampradhan Java
JoshCrozier JavaScript
ruoru Rust
suxrobGM C#
wisdompeak C++
yuanliu666 Kotlin
zfang399 C++
27 links | 15 authors | 9 languages

Videos

3 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

6 solutions   October 22, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality