A row of n light bulbs, numbered 1 to n, starts with every bulb off. You then do n rounds. In round r, you flip the switch of every bulb whose number is a multiple of r: bulb r, bulb 2r, bulb 3r, and so on. Flipping turns an off bulb on and an on bulb off.
So round 1 turns every bulb on, round 2 flips every second bulb, and the last round flips only bulb n. Return how many bulbs are on at the end.
Example 1
Input: n = 10 Output: 3 Why: bulbs 1, 4 and 9 stay on
2 more examples and the constraints
Example 2
Input: n = 16 Output: 4 Why: the squares 1, 4, 9 and 16
Example 3
Input: n = 2 Output: 1 Why: round 2 turns bulb 2 back off
Constraints
- 0 ≤ n ≤ 1,000,000,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Count the squares one by oneO(√n)
- Take the square rootO(1)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for n = 1,000,000,000 | Verdict |
|---|---|---|---|
| Count the squares one by one | O(√n) | Passes; 31,623 loop steps | |
| Take the square root | O(1) | Best; one sqrt and a check |
n = number of bulbs. Simulating the rounds would be O(n log n), far too slow here.
Edge cases to test
- n = 0. There are no bulbs, so the answer is 0.
- n is a square. n = 25 counts bulb 25 itself: the answer is 5.
- Just below a square. n = 24 gives 4, since 25 is out of range.
- The largest n. √1,000,000,000 ≈ 31,622.8, so the answer is 31,622. (r + 1)² is just over 10⁹, so compute it in 64 bits to be safe.
Common mistakes
- Simulating every round, which takes billions of flips for the largest n.
- Trusting a floating-point square root blindly near huge perfect squares.
- Counting bulbs with an even number of divisors instead of an odd one.
How to talk through it
- 1Clarify. Does round 1 flip every bulb? Can n be 0? How large can n get?
- 2Simulate small. Try n = 10 by hand and notice bulbs 1, 4 and 9 are the only ones on.
- 3Explain why. Bulb k is flipped once per divisor; divisors pair up except for squares.
- 4Turn it into a formula. Count squares up to n: the whole part of √n, with a check against float error.
- 5Test out loud. Run n = 0, 2, 10 and 16, and check 0, 1, 3 and 4.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?