Skip to content
Problem 672 · LeetCode 672(opens in a new tab)

Bulb Switcher II

MediumBit manipulation

A room has n bulbs labelled 1 to n, and all of them start switched on. A panel has four buttons. Button 1 toggles every bulb. Button 2 toggles the bulbs with even labels. Button 3 toggles the bulbs with odd labels. Button 4 toggles the bulbs labelled 1, 4, 7, 10 and so on (labels that leave remainder 1 when divided by 3).

You must press buttons exactly presses times in total, choosing any button each time. Return how many different on/off patterns the bulbs could end up in.

Example 1

Input:  n = 3, presses = 2
Output: 7
Why:    every pattern of 3 bulbs except off, on, on
2 more examples and the constraints

Example 2

Input:  n = 5, presses = 0
Output: 1
Why:    no presses, so every bulb stays on

Example 3

Input:  n = 2, presses = 3
Output: 4
Why:    both bulbs can be on or off in every mix

Constraints

  • 1 ≤ n ≤ 1,000
  • 0 ≤ presses ≤ 1,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Simulate press by pressO(presses)
  2. Try the 16 button subsetsO(1)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 1,000 pressesVerdict
Simulate press by pressO(presses)
Passes; one round per press
Try the 16 button subsetsO(1)
Best; same work for any input

Both look at only min(n, 6) bulbs.

Edge cases to test

  • No presses. presses = 0 leaves one pattern, all on, whatever n is.
  • One bulb. n = 1 can only be on or off, so the answer is at most 2.
  • Many presses. n = 1,000 and presses = 1,000 gives 8; the count stops growing after 3 presses.
  • Odd presses. With presses = 1, the empty subset is not allowed: you must press something.

Common mistakes

  • Simulating all n bulbs and all 4^presses press orders, which explodes.
  • Forgetting the parity rule, so presses = 1 wrongly counts the all-on pattern.
  • Mixing up labels and indices: bulb 1 is index 0, so "even labels" are the odd indices.

How to talk through it

  1. 1Clarify. Exactly presses presses, any button each time, and bulbs start on?
  2. 2Shrink the input. The buttons repeat every 6 bulbs, so n can be cut to min(n, 6).
  3. 3Shrink the presses. Order does not matter and pairs cancel, so only the odd-pressed subset matters: 16 cases.
  4. 4Code the enumeration. Check size ≤ presses and matching parity, apply the buttons, count distinct patterns.
  5. 5Test out loud. Run presses = 0, n = 1, and n = 3 with one press.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?