The Bulb Switcher interview question is a famous brainteaser. You start with n bulbs that are all off. You perform n rounds of switching. In the i-th round, you toggle every i-th bulb. The goal is to find how many bulbs remain ON after n rounds. This Bulb Switcher coding problem is more about mathematical deduction than complex data structures.
Companies like Microsoft and Amazon use this to see if a candidate can look past the simulation and find an underlying mathematical pattern. It tests your ability to think critically about factors and divisors. Most interviewers don't actually want you to simulate the toggling; they want you to realize the "Perfect Square" property.
This utilizes the Brainteaser, Math interview pattern. A bulb at position x is toggled once for every divisor of x. For example, bulb 6 is toggled at rounds 1, 2, 3, and 6 (4 times). Since 4 is even, it ends up OFF. Only numbers with an odd number of divisors remain ON. Mathematically, only perfect squares have an odd number of divisors. Thus, the problem reduces to counting the perfect squares up to n, which is simply floor(sqrt(n)).
Let n = 5.
When you see a problem involving toggling states based on multiples or factors, investigate the properties of divisors. Many such problems boil down to whether a number has an even or odd number of factors.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Moving Stones Until Consecutive | Medium | Solve | |
| Strictly Palindromic Number | Medium | Solve | |
| Nim Game | Easy | Solve | |
| Count Total Number of Colored Cells | Medium | Solve | |
| Factorial Trailing Zeroes | Medium | Solve |