Bulb Switcher - Problem

There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb.

On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the i-th round, you toggle every i-th bulb.

For the n-th round, you only toggle the last bulb.

Return the number of bulbs that are on after n rounds.

Input & Output

Example 1 — Small Case
$ Input: n = 3
Output: 1
💡 Note: Initial: [OFF,OFF,OFF]. Round 1: [ON,ON,ON]. Round 2: [ON,OFF,ON]. Round 3: [ON,OFF,OFF]. Only bulb 1 stays on.
Example 2 — Perfect Square
$ Input: n = 9
Output: 3
💡 Note: Perfect squares 1, 4, 9 have odd number of divisors, so they remain on after all toggles.
Example 3 — Edge Case
$ Input: n = 0
Output: 0
💡 Note: No bulbs means 0 bulbs are on.

Constraints

  • 0 ≤ n ≤ 109

Visualization

Tap to expand
Bulb Switcher Problem INPUT Initial State: n = 3 bulbs Bulb 1 Bulb 2 Bulb 3 All OFF initially Input Values n = 3 3 rounds, 3 bulbs Toggles per bulb: B1:1,2,3 | B2:1,2 | B3:1,3 divisors determine toggles ALGORITHM STEPS 1 Round 1: Toggle ALL All bulbs ON: [ON,ON,ON] 2 Round 2: Every 2nd Toggle 2: [ON,OFF,ON] 3 Round 3: Every 3rd Toggle 3: [ON,OFF,OFF] 4 Count ON bulbs Only bulb 1 is ON Toggle Pattern Round B1 B2 B3 1 2 3 Yellow=ON, Gray=OFF FINAL RESULT Final State After 3 Rounds ON OFF OFF Output 1 bulb remains ON OK - Verified! sqrt(3) = 1.73 --> 1 Key Insight: A bulb is ON only if toggled an ODD number of times. This happens only for PERFECT SQUARES because they have an odd number of divisors (e.g., 1 has divisor {1}, 4 has {1,2,4}). Optimal Solution: Return floor(sqrt(n)) -- O(1) time complexity! TutorialsPoint - Bulb Switcher | Optimal Solution: O(1)
Asked in
Google 25 Microsoft 20 Apple 15
38.5K Views
Medium Frequency
~15 min Avg. Time
892 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