Bulb Switcher - Problem
The Great Bulb Switching Challenge!

Imagine you have n light bulbs arranged in a row, all initially turned off. You're about to perform a fascinating switching ritual:

๐Ÿ”ด Round 1: Turn on ALL bulbs (every 1st bulb)
๐ŸŸก Round 2: Toggle every 2nd bulb (positions 2, 4, 6, ...)
๐ŸŸข Round 3: Toggle every 3rd bulb (positions 3, 6, 9, ...)
โญ Round i: Toggle every i-th bulb
๐ŸŽฏ Round n: Toggle only the last bulb

After completing all n rounds, your task is to count how many bulbs are still ON.

Note: "Toggle" means switching the state - if a bulb is ON, turn it OFF, and if it's OFF, turn it ON.

Input & Output

example_1.py โ€” Small Case
$ Input: n = 3
โ€บ Output: 1
๐Ÿ’ก Note: Initially [OFF,OFF,OFF]. Round 1: toggle all โ†’ [ON,ON,ON]. Round 2: toggle every 2nd โ†’ [ON,OFF,ON]. Round 3: toggle every 3rd โ†’ [ON,OFF,OFF]. Only bulb 1 (position 1) remains ON. Result: 1
example_2.py โ€” Medium Case
$ Input: n = 6
โ€บ Output: 2
๐Ÿ’ก Note: After all rounds, only bulbs at positions 1 and 4 remain ON. These are perfect squares (1ยฒ = 1, 2ยฒ = 4). Perfect squares โ‰ค 6: {1, 4}. Count = 2
example_3.py โ€” Edge Case
$ Input: n = 0
โ€บ Output: 0
๐Ÿ’ก Note: No bulbs means no bulbs can be ON. Result: 0

Visualization

Tap to expand
Answer = floor(โˆšn)Perfect Squares Pattern Visualizationn = 16 example:Perfect squares โ‰ค 16:11ยฒ=142ยฒ=493ยฒ=9164ยฒ=16Count = 4Non-perfect squares (some examples):2356All OFFWhy Perfect Squares Stay ON:โ€ข Regular numbers have even divisor count: (1,12), (2,6), (3,4) โ†’ 6 divisorsโ€ข Perfect squares have odd divisor count: (1,9), (3,3) โ†’ 3 divisors (3 pairs with itself)โ€ข Even toggles = OFF, Odd toggles = ON
Understanding the Visualization
1
Divisor Insight
Each bulb i gets toggled once for every divisor of i
2
Pairing Pattern
Divisors usually come in pairs (d, n/d), giving even counts
3
Special Case
Perfect squares have one divisor (โˆšn) that pairs with itself
4
Final State
Only odd toggle counts (perfect squares) remain ON
Key Takeaway
๐ŸŽฏ Key Insight: Only perfect squares have an odd number of divisors, so only they remain ON after all switching rounds!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(1)

Just computing the square root of n, which is a constant time operation

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using a few variables to store the result

n
2n
โœ“ Linear Space

Constraints

  • 0 โ‰ค n โ‰ค 109
  • Large inputs require O(1) solution
Asked in
Google 15 Microsoft 12 Amazon 8 Apple 6
31.8K Views
Medium Frequency
~15 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen