Bulb Switcher — Solution in Python, Java & C++
Bulb Switcher solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. A medium problem on math and brainteaser.
Bulb Switcher is a medium coding problem on math and brainteaser, asked in Amazon, Google, Microsoft and MathWorks interviews.
- Difficulty: Medium
- Topics: Math, Brainteaser
- Asked at: Amazon, Google, Microsoft, MathWorks
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
There are n bulbs, all off. You do n rounds:
- round 1 toggles every bulb;
- round 2 toggles every 2nd bulb;
- round
itoggles everyi-th bulb; - round
ntoggles only the last bulb.
Return how many bulbs are on after n rounds.
Example 1
Input: n = 3
Output: 1
Explanation: Only bulb 1 stays on.
Example 2
Input: n = 0
Output: 0
Example 3
Input: n = 1
Output: 1
Constraints
0 <= n <= 1000000000
Hints for Bulb Switcher
Hint 1
Bulb
kis toggled once per divisor ofk, so it ends up on exactly whenkhas an odd number of divisors.Hint 2
Divisors normally pair up — except when the two halves of a pair coincide.
Hint 3
That happens only for perfect squares, so the answer is
floor(sqrt(n)).
How to solve Bulb Switcher
Bulb k is toggled once per divisor of k, so it stays on iff k has an odd number of divisors — exactly the perfect squares. Answer: ⌊√n⌋.
Approach
- Return the integer square root of
n.
Why it works
Divisors pair up as (d, k/d) except when d = k/d, so only squares have an odd divisor count; the squares up to n number ⌊√n⌋.
Complexity
- Time —
O(1) - Space —
O(1)
Pitfalls
- Use an integer square root; floating-point
sqrtcan be off by one at largen.
Reference solution
Python
import math
def bulbSwitch(n: int) -> int:
return math.isqrt(n)Java
public static int bulbSwitch(int n) {
long root = (long) Math.sqrt((double) n);
while ((root + 1) * (root + 1) <= n) root++;
while (root > 0 && root * root > n) root--;
return (int) root;
}C++
int bulbSwitch(int n) {
long long root = (long long) sqrt((double) n);
while ((root + 1) * (root + 1) <= n) root++;
while (root > 0 && root * root > n) root--;
return (int) root;
}JavaScript
var bulbSwitch = function(n) {
let root = Math.floor(Math.sqrt(n));
while ((root + 1) * (root + 1) <= n) root++;
while (root * root > n) root--;
return root;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.