Bulb Switcher Problem
Description
LeetCode Problem 319.
There are n bulbs that are initially off. You first turn on all the bulbs, thenyou 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 bulb. For the n^th round, you only toggle the last bulb.
Return the number of bulbs that are on after n rounds.
Example 1:
Input: n = 3
Output: 1
Explanation: At first, the three bulbs are [off, off, off].
After the first round, the three bulbs are [on, on, on].
After the second round, the three bulbs are [on, off, on].
After the third round, the three bulbs are [on, off, off].
So you should return 1 because there is only one bulb is on.
Example 2:
Input: n = 0
Output: 0
Example 3:
Input: n = 1
Output: 1
Constraints:
- 0 <= n <= 10^9
Solution
Approach: Count the Perfect Squares
Simulating the rounds toggles about n log n bulbs in total, far too many when n can be 109. Instead, look at a single bulb.
Bulb i is toggled in round d exactly when d divides i. It starts off, so it ends on exactly when it is toggled an odd number of times, that is, when i has an odd number of divisors.
Divisors come in pairs: if d divides i, so does i / d. For 12 the pairs are (1, 12), (2, 6), (3, 4), an even count. The only way to get an odd count is a pair whose two halves are equal, d = i / d, which happens exactly when i is a perfect square: 9 has divisors 1, 3, 9.
So the bulbs left on are those at positions 1, 4, 9, 16, ..., and the number of perfect squares from 1 to n is floor(sqrt(n)).
Example: for n = 3 only bulb 1 is a square, so the answer is 1. For n = 0 there are no bulbs and the answer is 0.
Taking the square root in floating point is exact enough here: for n up to 109, sqrt(n) of a perfect square is computed exactly, and a non-square is never rounded up to the next integer.
Complexity: O(1) time and O(1) space.
import math
class Solution:
def bulbSwitch(self, n: int) -> int:
# Bulb i ends on exactly when i has an odd number of divisors, i.e. when i is a perfect square.
# The squares 1, 4, 9, ... up to n number floor(sqrt(n)).
return int(math.sqrt(n))
Now write it from memory
Close the write-up and solve it yourself against the tests.