Bulb Switcher (LeetCode 319): Solution and Explanation
n bulbs start off; round k flips every k-th bulb for k = 1 to n. Count the bulbs that are on at the end. The answer is the number of perfect squares up to n.
Intuition
Simulating n rounds over n bulbs is O(n log n) at best and n can be 10^9, so look at one bulb instead of one round.
Bulb i is flipped in round k exactly when k divides i. So the number of flips of bulb i is the number of divisors of i, and it ends on when that number is odd.
Divisors come in pairs: if a divides i then so does i / a. Every pair contributes two flips, which cancel out.
The only way to get an odd count is a pair where a = i / a, that is a * a = i. So exactly the perfect squares end on, and there are floor(sqrt(n)) of them up to n.
Approach: Count the perfect squares
- Observe that bulb i ends on iff i is a perfect square.
- The squares up to n are 1^2, 2^2, ..., k^2 where k = floor(sqrt(n)).
- Return k, computed with an integer square root.
Step-by-step example
n = 3
- Round 1 flips bulbs 1, 2, 3: all on.
- Round 2 flips bulb 2: it goes off.
- Round 3 flips bulb 3: it goes off. Only bulb 1 is on.
- Check with divisors: 1 has {1} (odd), 2 has {1, 2} and 3 has {1, 3} (even).
- isqrt(3) = 1, the single square 1. The answer is 1.
Code: Python, Java, C++
1class Solution:
2 def bulbSwitch(self, n: int) -> int:
3 root = math.isqrt(n)
4 return root1class Solution {
2 public int bulbSwitch(int n) {
3 int root = (int) Math.sqrt(n);
4 return root;
5 }
6}1class Solution {
2public:
3 int bulbSwitch(int n) {
4 int root = (int) sqrt((double) n);
5 return root;
6 }
7};Time and space complexity
O(1)
One square root computation, no matter how large n is.
O(1)
Only a single number is stored.
Other approaches
Simulate every round (time O(n log n), space O(n))
Keep an array of n booleans and flip multiples of k for each k. It confirms the pattern on small n but takes O(n log n) time and O(n) memory, far too much for n = 10^9.
Count squares with a loop (time O(sqrt n), space O(1))
Increase k while k * k <= n and count. Exact with no floating point, and about 31,623 steps at the limit.
Common mistakes
- Trying to simulate. n can be 10^9, so even one pass over the bulbs is too slow.
- Floating point square roots on very large inputs. For n up to 10^9 a double is exact enough, but an integer square root (or a correction step) is the safe habit.
- Forgetting n = 0, which has no bulbs and must return 0.
Frequently asked questions
Why does a perfect square have an odd number of divisors?
Divisors pair up as a and i / a. For a perfect square, the divisor sqrt(i) pairs with itself, so it is counted once instead of twice, which makes the total odd.
Is Math.sqrt safe here?
Yes for n up to 10^9: doubles represent these integers exactly and the square root of a perfect square comes out exact. For much larger values use an integer square root.
What does the answer look like for n = 10?
The squares 1, 4 and 9 are at most 10, so 3 bulbs stay on.