title: Bulb Switcher II
slug: bulb-switcher-ii
difficulty: medium
leetcode_id: 672
leetcode_url: https://leetcode.com/problems/bulb-switcher-ii/
categories:
  - math
patterns:
  - greedy

description: |
  There is a room with `n` bulbs labelled 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:

  - **Button 1:** Flips the status of all the bulbs.
  - **Button 2:** Flips the status of all the bulbs with even labels (i.e., `2, 4, ...`).
  - **Button 3:** Flips the status of all the bulbs with odd labels (i.e., `1, 3, ...`).
  - **Button 4:** Flips the status of all the bulbs with a label `j = 3k + 1` where `k = 0, 1, 2, ...` (i.e., `1, 4, 7, 10, ...`).

  You must make **exactly** `presses` button presses in total. For each press, you may pick **any** of the four buttons to press.

  Given the two integers `n` and `presses`, return *the number of **different possible statuses** after performing all* `presses` *button presses*.

constraints: |
  - `1 <= n <= 1000`
  - `0 <= presses <= 1000`

examples:
  - input: "n = 1, presses = 1"
    output: "2"
    explanation: "Status can be: [off] by pressing button 1, or [on] by pressing button 2 (even bulbs only, so bulb 1 is unaffected)."
  - input: "n = 2, presses = 1"
    output: "3"
    explanation: "Status can be: [off, off] by pressing button 1, [on, off] by pressing button 2, or [off, on] by pressing button 3."
  - input: "n = 3, presses = 1"
    output: "4"
    explanation: "Status can be: [off, off, off] by button 1, [on, off, on] by button 2, [off, on, off] by button 3, or [off, on, on] by button 4."

explanation:
  intuition: |
    At first glance, this problem seems to require simulating all possible sequences of button presses — potentially exponential in complexity. But there's a beautiful mathematical insight that reduces this to a simple case analysis.

    The key observations are:

    **1. Pressing a button twice cancels out.** Each button is essentially a toggle. Pressing button 1 twice returns all bulbs to their original state. This means we only care about whether each button is pressed an **odd or even** number of times — effectively a binary choice per button.

    **2. The order of presses doesn't matter.** Since each button acts independently (toggling certain bulbs), the final state depends only on *which* buttons were pressed an odd number of times, not the sequence.

    **3. Only the first 3 bulbs determine uniqueness.** Bulbs follow repeating patterns based on the button rules:
    - Button 1 affects all bulbs
    - Button 2 affects even-labelled bulbs (2, 4, 6, ...)
    - Button 3 affects odd-labelled bulbs (1, 3, 5, ...)
    - Button 4 affects bulbs at positions `3k + 1` (1, 4, 7, ...)

    The pattern of which buttons affect which bulbs repeats every 6 positions. However, to count *distinct* states, we only need to look at bulbs 1, 2, and 3 — the state of these three bulbs uniquely determines the overall configuration pattern.

    With these insights, the problem becomes: given `presses` button presses, how many distinct combinations of (odd/even presses per button) can we achieve, considering we must use exactly `presses` total presses?

  approach: |
    We solve this using **Mathematical Case Analysis** based on the number of bulbs and presses:

    **Step 1: Handle the base case**

    - If `presses = 0`, no buttons are pressed, so all bulbs remain on — only **1** possible state

    &nbsp;

    **Step 2: Analyse by number of bulbs**

    The answer depends on both `n` (bulbs) and `presses`. We consider three cases based on `n`:

    &nbsp;

    **Case: n = 1 (single bulb)**

    - Only button 1 and button 4 affect bulb 1 (both toggle it)
    - Button 2 has no effect (no even-labelled bulbs)
    - Button 3 toggles bulb 1
    - With 1 press: 2 states (on or off)
    - With 2+ presses: 2 states (the parity determines on/off)

    &nbsp;

    **Case: n = 2 (two bulbs)**

    - Bulb 1: affected by buttons 1, 3, 4
    - Bulb 2: affected by buttons 1, 2
    - With 1 press: 3 states (each of buttons 1, 2, 3 gives a unique state; button 4 = button 3 for these bulbs)
    - With 2 presses: 4 states
    - With 3+ presses: 4 states (all reachable combinations achieved)

    &nbsp;

    **Case: n >= 3 (three or more bulbs)**

    - All four buttons have distinct effects
    - With 1 press: 4 states (one per button)
    - With 2 presses: 7 states
    - With 3+ presses: 8 states (all 2^3 combinations of the 3 representative bulbs, though limited by parity)

    &nbsp;

    **Step 3: Return the result based on case analysis**

    - Use conditional logic to return the correct count based on `n` and `presses`

  common_pitfalls:
    - title: Simulating All Button Sequences
      description: |
        A naive approach tries to simulate all possible sequences of `presses` button presses. With 4 buttons and up to 1000 presses, this means `4^1000` possibilities — astronomically large and completely infeasible.

        The key insight is that order doesn't matter and pressing twice cancels out, so we only need to consider which buttons are pressed an odd number of times.
      wrong_approach: "BFS/DFS exploring all press sequences"
      correct_approach: "Mathematical case analysis based on parity"

    - title: Considering All n Bulbs Independently
      description: |
        You might think you need to track the state of all `n` bulbs separately. But since the button patterns repeat, only the first 3 bulbs matter for determining distinct states.

        For example, bulb 4 behaves exactly like bulb 1 under buttons 1-3, and bulbs 5, 6 follow bulbs 2, 3 respectively. Button 4 adds some variation but the pattern still cycles.
      wrong_approach: "Tracking state of all n bulbs"
      correct_approach: "Analyse only the first 3 bulbs as representatives"

    - title: Forgetting the Parity Constraint
      description: |
        When `presses` is odd, you must press an odd total number of buttons. When `presses` is even, you must press an even total. This constrains which combinations are reachable.

        For instance, with `presses = 1`, you can't press two buttons to cancel each other out — you must change something.
      wrong_approach: "Ignoring how presses constrains reachable states"
      correct_approach: "Consider parity when counting achievable combinations"

  key_takeaways:
    - "**Pattern recognition over simulation**: When the state space seems huge, look for mathematical structure that reduces the problem"
    - "**Toggle operations have special properties**: Pressing twice cancels out, order doesn't matter — this is XOR-like behaviour"
    - "**Periodicity reduces complexity**: When operations follow repeating patterns, analyse one period rather than the entire input"
    - "**Case analysis is valid**: Sometimes the cleanest solution is carefully enumerating small cases rather than finding a general formula"

  time_complexity: "O(1). The solution uses direct case analysis with constant-time conditionals, regardless of the input values."
  space_complexity: "O(1). Only a few variables are used for the conditional logic."

solutions:
  - approach_name: Mathematical Case Analysis
    is_optimal: true
    code: |
      def flip_lights(n: int, presses: int) -> int:
          # Base case: no presses means all bulbs stay on
          if presses == 0:
              return 1

          # Only 1 bulb: can be on or off (2 states max)
          if n == 1:
              return 2

          # 2 bulbs: limited combinations possible
          if n == 2:
              # 1 press: 3 distinct states achievable
              if presses == 1:
                  return 3
              # 2+ presses: all 4 combinations of 2 bulbs reachable
              return 4

          # n >= 3: pattern is determined by first 3 bulbs
          if presses == 1:
              # 4 buttons = 4 distinct single-press states
              return 4
          if presses == 2:
              # 7 states achievable with exactly 2 presses
              return 7

          # 3+ presses: all 8 possible states of 3 bulbs reachable
          return 8
    explanation: |
      **Time Complexity:** O(1) — Direct conditionals with no loops.

      **Space Complexity:** O(1) — No additional data structures.

      This solution leverages the mathematical insight that the problem reduces to a small number of cases based on `n` and `presses`. The key observations are:
      1. Only the first 3 bulbs matter for distinguishing states
      2. Button presses are commutative and self-cancelling
      3. The achievable states are constrained by parity

  - approach_name: BFS Simulation (For Verification)
    is_optimal: false
    code: |
      def flip_lights(n: int, presses: int) -> int:
          # Limit n to 3 since pattern repeats
          n = min(n, 3)

          # Start with all bulbs on (represented as tuple of 1s)
          start = tuple([1] * n)

          # Define button effects on first 3 bulbs
          def press_button(state: tuple, button: int) -> tuple:
              state = list(state)
              for i in range(len(state)):
                  bulb_num = i + 1  # 1-indexed bulb number
                  if button == 1:  # All bulbs
                      state[i] ^= 1
                  elif button == 2 and bulb_num % 2 == 0:  # Even bulbs
                      state[i] ^= 1
                  elif button == 3 and bulb_num % 2 == 1:  # Odd bulbs
                      state[i] ^= 1
                  elif button == 4 and (bulb_num - 1) % 3 == 0:  # 3k+1 bulbs
                      state[i] ^= 1
              return tuple(state)

          # BFS to find all reachable states after exactly 'presses' presses
          current_states = {start}
          for _ in range(presses):
              next_states = set()
              for state in current_states:
                  for button in range(1, 5):
                      next_states.add(press_button(state, button))
              current_states = next_states

          return len(current_states)
    explanation: |
      **Time Complexity:** O(presses × states × buttons) — In practice O(presses) since states ≤ 8.

      **Space Complexity:** O(states) — At most 8 states tracked.

      This BFS approach simulates all possible button press sequences level by level. While not necessary for the final solution, it's useful for verifying the mathematical analysis and understanding why certain state counts are achieved. The key optimisation is limiting `n` to 3 since larger values don't create new distinct patterns.
