Problem 319

Abstract / Summary

A room has n bulbs switched by n people each toggling certain bulbs and the question is how many bulbs remain on after all have acted.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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)
4 lines | 160 bytes | submitted September 10, 2023 | GitHub   33% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 56% (500k+ submissions).

Typical patterns to solve this problem:
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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 Solution follows 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.5 computes the square root of n using Python’s exponentiation operator. Wrapping this result with int() 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 9 | μ = 8.70 | σ = 1.05

Complexity Analysis

Time: constant
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
38 links | 24 authors | 10 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

3 easy 1 medium 1 hard
6 solutions   September 10, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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