Python 0319.py
class Solution:
def bulbSwitch(self, n: int) -> int:
# brute-force shows that bulbs at position n^2 are on, else off
return int(n**0.5)
Difficulty
and has an acceptance rate of about 56% (500k+ submissions).
Typical patterns to solve this problem:
- Math
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a Solution class with a single method bulbSwitch. The method receives an integer n and returns the count of bulbs that remain on after a series of toggling operations. The core insight leveraged by the code is that only bulbs positioned at perfect squares stay illuminated, which translates mathematically to the integer part of the square root of n. The implementation captures this insight in a concise, single-line return statement.
Key Steps
The method consists of three logical components: class definition, method signature with type annotation, and the computation itself.
class Solution:
def bulbSwitch(self, n: int) -> int:
# brute-force shows that bulbs at position n^2 are on, else off
return int(n**0.5)
- The class wrapper
Solutionfollows the conventional pattern used by many coding platforms, allowing the method to be invoked as an instance method. - The method signature
def bulbSwitch(self, n: int) -> int:declares the expected input type (int) and the return type (int), providing clear documentation for callers and static analysis tools. - The comment inside the method succinctly explains the mathematical observation that drives the solution: bulbs whose indices are perfect squares remain on.
- The expression
n**0.5computes the square root ofnusing Python’s exponentiation operator. Wrapping this result withint()truncates any fractional part, effectively performing a floor operation and yielding the count of perfect squares ≤n.
Edge Cases
The implementation gracefully handles several boundary conditions without additional branching logic.
When n is zero, the exponentiation yields 0.0; converting to int returns 0, correctly indicating that no bulbs are on. For n equal to one, the square root is 1.0, and the integer conversion yields 1, reflecting that the single bulb stays on. The use of the exponentiation operator automatically accommodates large values of n within the limits of Python’s floating-point representation, and the truncation step ensures that any non-integer square root is rounded down, preserving the correctness of the count.
Performance Characteristics
The algorithm operates in constant time because it performs a single arithmetic operation regardless of the magnitude of n. There are no loops, recursion, or auxiliary data structures, which eliminates overhead associated with iterative processing. The use of the built-in exponentiation operator leverages highly optimized native code paths for floating-point arithmetic, providing fast execution. Memory consumption is minimal, limited to the storage of the input parameter and the temporary floating-point result before conversion, resulting in a negligible footprint.
ELI5 - Simplified Explanation
Imagine a very long hallway with many light bulbs hanging from the ceiling. At the start, every single light bulb is dark. You have a special mission to walk down the hallway multiple times to flip switches on and off. On the first pass, you flip every single switch. On the second pass, you flip every second switch. You keep doing this until you have made as many passes as there are bulbs in the hallway.
When you finish your work and look back at the hallway, some lights are glowing brightly while others are dark. The code looks for a clever way to guess how many lights stay on without doing all that walking. It uses a secret math trick to see which bulb positions stay lit. It turns out that only the bulbs at square numbers like one, four, or nine end up staying on. The code calculates the square root of the number of bulbs to find the answer.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | Go | TS | ||||||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | black-shadows | C++ | |||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| everthis | JS | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| martianoff | Scala | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| everthis | JavaScript | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| martianoff | Scala | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 672: Bulb Switcher II
- problem 995: Minimum Number of K Consecutive Bit Flips
- problem 2485: Find the Pivot Integer
Solved On The Same Day
- problem 661: Image Smoother
- problem 693: Binary Number with Alternating Bits
- problem 762: Prime Number of Set Bits in Binary Representation
- problem 2336: Smallest Number in Infinite Set
- problem 679: 24 Game
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality