#319
Bulb Switcher
MediumMathBrainteaserMathBrainteaser
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(1) |
| Space | O(n) | O(1) |
💡
Intuition
Time O(1)Space O(1)
Instead of simulating each toggle, we can observe that a bulb's final state depends on the number of times it is toggled. A bulb at position k is toggled for each divisor it has. Only bulbs with an odd number of divisors remain on, which happens for perfect squares.
⚙️
Algorithm
3 steps- 1Step 1: The bulbs that remain on correspond to the perfect squares up to n.
- 2Step 2: The number of perfect squares less than or equal to n is given by the integer part of the square root of n.
- 3Step 3: Return the integer part of the square root of n.
solution.py4 lines
1import math
2
3def bulbSwitch(n):
4 return int(math.sqrt(n))ℹ
Complexity note: The time complexity is O(1) because we are only calculating the square root of n, which is a constant time operation. The space complexity is O(1) since we are using a fixed amount of space.
- 1Only bulbs at positions that are perfect squares remain on after all rounds.
- 2The number of bulbs that remain on is equal to the largest integer k such that k² ≤ n.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.