Bulb Switcher

Bulb i ends on iff i has an odd number of divisors — iff i is a perfect square. Answer is floor(sqrt(n)).

Medium
Time O(1) Space O(1)
LeetCode
1 min read
math number-theory

Problem#

n bulbs, all off. In round k (1-indexed), toggle every k-th bulb. After n rounds, how many bulbs are on?

Examples#

  • n=31.
  • n=00; n=11.

Constraints#

  • 0 <= n <= 10^9.

Approach#

Bulb i is toggled once per divisor of i. It ends on iff that count is odd. A positive integer has an odd number of divisors iff it’s a perfect square (divisors pair as (d, i/d) except when d = i/d). So count perfect squares <= n: floor(sqrt(n)).

Solution#

Bulb Switcher
class Solution {
public:
int bulbSwitch(int n) {
return (int)sqrt((double)n);
}
};

Editorial#

A pure number-theory collapse — the simulation would be O(n log n) but the closed form is O(1). The divisor-pairing argument is the standard proof that perfect squares uniquely have an odd divisor count.

Complexity#

  • Time: O(1).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.