Python 1375.py
class Solution:
def numTimesAllBlue(self, flips: List[int]) -> int:
result = 0
high = 0 # highest flipped position so far
for i, f in enumerate(flips, start = 1):
high = max(high, f)
if high == i:
result += 1 # all flips happened "on the left side"
return result
Difficulty
and has an acceptance rate of about 66% (90k+ submissions).
Typical patterns to solve this problem:
- Array
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 solves the problem of counting moments when all bulbs up to the current position are turned on after a sequence of flips. It processes the input list in a single forward pass, maintaining only a few integer variables. The logic hinges on tracking the furthest position that has been flipped and comparing it with the number of flips processed so far. When these two values coincide, it indicates that every position from the start up to that point has been turned on, and the result counter is incremented.
Key Steps
Initialization
At the beginning, the method creates a counter for successful moments (result) and a variable to store the highest index that has been flipped (high). Both are set to zero, establishing a clean baseline before any input is examined.
result = 0
high = 0 # highest flipped position so far
Iteration Over Flips
The core of the algorithm is a loop that enumerates the flips list starting from one, which aligns the loop index with the natural 1-based position count used in the problem statement. For each iteration, the current flip position f is compared with the stored high. The max function updates high only when a new farther position appears, ensuring that high always reflects the rightmost bulb that has been turned on up to the current step.
for i, f in enumerate(flips, start=1):
high = max(high, f)
Detecting Complete Prefixes
Immediately after updating high, the algorithm checks whether the highest flipped position equals the number of flips processed (i). Equality means that all positions from 1 through i have been flipped, because no position beyond i could have been turned on without leaving a gap. When this condition holds, the result counter is incremented, marking a moment when the prefix of bulbs is fully blue.
if high == i:
result += 1 # all flips happened "on the left side"
Final Result
After the loop finishes, the method returns the accumulated count of moments where the prefix condition was satisfied. This single return statement delivers the answer directly to the caller.
return result
Edge Cases Handled
The algorithm gracefully handles scenarios where the flip order is completely reversed, such as flipping the farthest bulb first and then progressively moving leftward. In such a case, high will be set to the maximum index on the first iteration, but the equality check will fail until the loop index catches up, ensuring that only the correct moments are counted.
When the input list contains a single element, the loop runs once, high becomes that element, and the equality test succeeds because both high and the loop index are one, resulting in a count of one.
If the flips are already in ascending order, high will increase in lockstep with the loop index, causing the equality condition to be true at every step. The code correctly records a moment for each flip without any additional logic.
The implementation also works when the list contains duplicate values or values outside the expected range, because the max operation simply retains the greatest seen value, and the equality check remains the decisive factor. The loop’s enumeration guarantees that the index i always reflects the number of processed flips, preserving correctness regardless of the specific values encountered.
Performance Optimizations
The solution achieves optimal efficiency by limiting itself to a single traversal of the input list. All work is performed inside the loop, with each iteration executing only a constant amount of arithmetic and a single comparison. No auxiliary data structures such as sets, arrays, or hash maps are allocated, which keeps the memory footprint minimal.
By using the built-in max function, the code leverages a highly optimized primitive for updating the highest flipped position, avoiding manual conditional branches. The equality check (high == i) is a simple integer comparison, which is extremely fast on modern processors.
Because the algorithm does not need to revisit any element after it has been processed, it avoids any hidden quadratic behavior that could arise from nested loops or repeated scans. The overall design ensures that the runtime scales linearly with the length of the flips list, while the auxiliary storage remains constant throughout execution.
ELI5 - Simplified Explanation
Imagine a long row of light bulbs that are all turned off. There is a helper who comes by one by one and turns on specific bulbs based on a list. The goal is to see how many times every bulb that is currently turned on is located in a perfect, solid line starting from the very first one on the far left.
The code keeps track of the bulb that is furthest to the right among all the ones that have been turned on so far. It also keeps track of how many bulbs have been turned on in total. If the number of the furthest bulb matches the number of total bulbs that have been turned on, it means there are no gaps or dark spots in the line. Every single bulb from the start to that furthest point is shining bright blue. Whenever this happens, a counter goes up by one to record that the lights look perfect at that moment. The process continues until every bulb in the list has been flipped.
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 | Go | Java | TS | |||
| Progiez | C++ | Python | Java | |||||
| github | BigEggStudy | C# | ||||||
| everthis | JS | |||||||
| fpdjsns | C++ | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| lzl124631x | C++ | |||||||
| trung-hn | Python | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| BigEggStudy | C# | |||||||
| everthis | JavaScript | |||||||
| fpdjsns | C++ | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| lzl124631x | C++ | |||||||
| trung-hn | Python |
Videos
Similar Problems
- problem 319: Bulb Switcher
- problem 672: Bulb Switcher II
Solved On The Same Day
- problem 2299: Strong Password Checker II
- problem 1899: Merge Triplets to Form Target Triplet
- problem 2348: Number of Zero-Filled Subarrays
- problem 2870: Minimum Number of Operations to Make Array Empty
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