DDSA Solutions

319. Bulb Switcher

Time: O(1)
Space: O(1)
Advertisement

Intuition

Bulb i is toggled by all its divisors. A bulb ends ON only if it has an odd number of divisors - which happens only for perfect squares. Count of perfect squares <= n = floor(√n).

Algorithm

  1. 1Return (int)Math.Sqrt(n).

Example Walkthrough

Input: n = 3

  1. 1.Perfect squares <= 3: 1. floor(√3)=1.
  2. 2.Only bulb 1 stays on.

Output: 1

Common Pitfalls

  • Use integer square root carefully - floating point sqrt(4) might give 1.9999... for some n.
319.cs
C#
// Approach: Only perfect-square positions have an odd number of divisors
// and remain on after all toggles; return floor(√n).
// Time: O(1) Space: O(1)

public class Solution
{
    public int BulbSwitch(int n)
    {
        return (int)Math.Sqrt(n);
    }
}
Advertisement
Was this solution helpful?