Bulb Switcher II - Problem
Imagine you're in a room with n bulbs labeled from 1 to n, all initially turned ON. On the wall, there are four special buttons that control the bulbs in different patterns:
- Button 1: Flips all bulbs (1, 2, 3, 4, ...)
- Button 2: Flips bulbs with even labels (2, 4, 6, 8, ...)
- Button 3: Flips bulbs with odd labels (1, 3, 5, 7, ...)
- Button 4: Flips bulbs at positions
3k + 1where k โฅ 0 (1, 4, 7, 10, ...)
You must press buttons exactly presses times. Each press can be any of the four buttons. Your goal is to determine how many different possible states the bulbs can be in after all button presses.
Example: With n=2 and presses=1, you could press button 1 (both bulbs OFF), button 2 (bulb 1 ON, bulb 2 OFF), or button 3 (bulb 1 OFF, bulb 2 ON), giving you 3 different states.
Input & Output
example_1.py โ Basic case
$
Input:
n = 1, presses = 1
โบ
Output:
4
๐ก Note:
With 1 bulb and 1 press: Button 1 โ [0], Button 2 โ [1] (no effect), Button 3 โ [0], Button 4 โ [0]. All 4 buttons give different results.
example_2.py โ Two bulbs
$
Input:
n = 2, presses = 1
โบ
Output:
3
๐ก Note:
Button 1 โ [0,0], Button 2 โ [1,0], Button 3 โ [0,1], Button 4 โ [0,1]. Buttons 3 and 4 give same result, so 3 unique states.
example_3.py โ Multiple presses
$
Input:
n = 3, presses = 2
โบ
Output:
7
๐ก Note:
With 2 presses, we can achieve combinations like pressing different buttons once each, or pressing one button twice (which cancels out). This creates 7 distinct final states.
Visualization
Tap to expand
Understanding the Visualization
1
Pattern Recognition
Notice that button effects follow mathematical patterns - even/odd positions, arithmetic sequences
2
Cancellation Discovery
Realize that pressing same button twice returns to original state
3
Periodicity Insight
Understand that the pattern repeats every 3 bulbs due to LCM of button patterns
4
State Space Reduction
Reduce from exponential to constant time by focusing on button press parities
Key Takeaway
๐ฏ Key Insight: Mathematical pattern recognition transforms an exponential problem into a constant-time solution by identifying button press cancellations and periodic bulb patterns.
Time & Space Complexity
Time Complexity
O(1)
Constant time as we only check fixed number of combinations
โ Linear Growth
Space Complexity
O(1)
Only store a few button states and bulb configurations
โ Linear Space
Constraints
- 1 โค n โค 1000
- 0 โค presses โค 1000
- All bulbs start in the ON state
- Button presses must be exactly equal to the given number
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code