Bulb Switcher

Medium

Topics
MathBrainteaser

There are n bulbs initially off. On round i you toggle every i-th bulb (round 1 toggles all). After n rounds, return how many bulbs are on. A bulb ends on iff it has an odd number of divisors, i.e. it is a perfect square.

Example 1

bulb123
still on at the end
Bulb k is toggled once per divisor of k, so it ends on only when k has an odd number of divisors — which happens exactly for perfect squares, since every other divisor comes in a pair. The answer is ⌊√3⌋ = 1.
Cells are bulb numbers; shaded bulbs are lit after all the rounds.
Input:  n = 3
Output: 1

Example 2

Input:  n = 0
Output: 0

Example 3

bulb123456789101112
still on at the end
Input:  n = 99
Output: 9

Constraints

  • 0 <= n <= 10^6
Editorial — intuition, approach, complexity and pitfalls

Intuition

Bulb k is toggled once for every divisor of k, so it ends on exactly when k has an odd number of divisors.

Divisors normally pair up — d with k/d — which makes the count even. The pairing fails in exactly one case: when d == k/d, that is when k is a perfect square and its square root pairs with itself. So the bulbs left on are precisely those at perfect-square positions, and the answer is the number of perfect squares up to n, which is floor(sqrt(n)).

k = 6:  divisors 1,2,3,6  -> four, pairs (1,6) (2,3)  -> off
k = 9:  divisors 1,3,9    -> three, 3 pairs with itself -> ON

The implementation takes a floating-point square root and then corrects it in both directions, because sqrt on a large integer can land a hair above or below the true root. That correction is the difference between a solution that works and one that fails on a boundary value.

Approach

  1. Take int(sqrt(n)) as a starting guess.
  2. Increase it while (r+1)^2 <= n; decrease it while r^2 > n.

Dry Run

n = 3   guess 1; 2*2 = 4 > 3 so no increase; 1 <= 3 so no decrease
        answer 1   (only bulb 1 stays on)

n = 0   answer 0
n = 1   answer 1

n = 10  guess 3; 4*4 = 16 > 10; 3*3 = 9 <= 10
        answer 3   (bulbs 1, 4, 9)

Complexity

  • Time — O(1): a square root and at most a couple of correction steps. Simulating the toggles would be O(n log n) and counting divisors per bulb O(n sqrt n).
  • Space — O(1).

Common Pitfalls

  • Simulating the rounds. Correct, and needless once the divisor-parity argument is seen.
  • Trusting int(sqrt(n)) without correction. Floating point can place the root just below an exact square, costing one from the answer.
  • Stating the answer as "perfect squares" without the reason. The follow-up is always why, and the answer is that divisors pair except at the square root.
  • Forgetting n = 0, which must give 0.

Full Solution — all languages

class Solution:
    def bulbSwitch(self, n):
        r = int(n ** 0.5)
        while (r + 1) * (r + 1) <= n:
            r += 1
        while r > 0 and r * r > n:
            r -= 1
        return r
Asked at LinkedIn
SensAI
Beta
Tap the mic to stop voice mode