Python 1004.py
class Solution:
def longestOnes(self, nums: List[int], k: int) -> int:
best = 0
left = -1
for right in range(len(nums)):
if nums[right] == 1:
best = max(best, right - left)
continue
# flip
if k > 0:
k -= 1
best = max(best, right - left)
continue
# move to next zero
left += 1
while nums[left] == 1:
left += 1
return best
Difficulty
and has an acceptance rate of about 67% (2+ million submissions).
Typical patterns to solve this problem:
- Array
- Binary Search
- Prefix Sum
- Sliding Window
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 classic “longest subarray with at most k zero flips” problem using a sliding-window technique. It maintains a dynamic window delimited by a left boundary (left) and a right boundary (right). As the right pointer advances through the array, the algorithm decides whether the current element can be incorporated directly, flipped from zero to one, or whether the window must be contracted to accommodate the flip budget k. The variable best records the maximum window length observed during the scan.
Initialization
At the start the algorithm sets best to zero, representing the longest valid window found so far, and initializes left to -1. The left pointer is positioned one step before the first element so that the length of a window that begins at index 0 can be computed as right - left. This choice simplifies length calculations throughout the loop.
best = 0
left = -1
Main Loop
The core of the solution is a single for loop that iterates right over every index of the input list nums. The loop body contains three distinct decision branches that correspond to the nature of the element at right and the remaining flip allowance k.
for right in range(len(nums)):
...
Handling Ones
When the element at the current right position is a 1, the window can be extended without consuming any flips. The algorithm updates best by comparing the current window length (right - left) with the previously recorded maximum. The continue statement skips the remaining logic for this iteration, ensuring that the window remains unchanged.
if nums[right] == 1:
best = max(best, right - left)
continue
Flipping Zeros
If the element is a 0 and there is at least one flip remaining (k > 0), the algorithm treats the zero as if it were a one by decrementing k. The window is again extended, and best is refreshed with the new length. The continue statement prevents any further adjustments for this iteration, effectively allowing the zero to be part of the current window.
if k > 0:
k -= 1
best = max(best, right - left)
continue
Sliding Window Adjustment
When a zero is encountered and no flips remain (k == 0), the window must be shifted forward to discard a previously flipped zero. The left pointer is incremented by one to move past the earliest zero that was flipped. Because the left pointer may land on a 1, a nested while loop advances it further until it reaches the next zero, thereby restoring one flip to the budget implicitly. This contraction ensures that the window always contains at most k flipped zeros.
left += 1
while nums[left] == 1:
left += 1
Edge Cases Handled
The algorithm gracefully handles several boundary conditions without additional code. An empty input list results in the loop body never executing, and best remains zero, which correctly reflects the length of the longest subarray. When the array consists entirely of ones, the first branch continuously updates best to the full length of the array, as no flips are needed. If the array contains only zeros and k is zero, the window never expands beyond a single element, and best stays at zero because the length calculation right - left yields zero for each isolated zero. When k exceeds the total number of zeros, the flip branch consumes all zeros, and the window eventually spans the entire array, yielding the maximum possible length. The initialization of left to -1 ensures that the length formula works uniformly for windows that start at index 0, eliminating off-by-one errors.
Performance Optimizations
The implementation achieves efficiency by updating the answer (best) incrementally as the right pointer moves, avoiding any need to recompute window lengths from scratch. The left pointer only moves forward, never backward, guaranteeing that each element is examined at most twice: once when the right pointer reaches it and possibly once more when the left pointer passes over it during contraction. This single-pass behavior eliminates redundant work. The use of simple integer arithmetic and direct list indexing keeps the inner operations lightweight, contributing to fast execution even on large inputs. Additionally, the early continue statements prevent unnecessary evaluation of later branches once a decision has been made for the current element, reducing the number of conditional checks per iteration.
ELI5 - Simplified Explanation
Imagine a long row of square tiles on the floor. Some of these tiles are orange with a number one on them, and some are grey with a zero. There is a magical wand that allows changing a few grey tiles into orange ones. The goal is to find the longest path of orange tiles that can be created.
Start by looking at the tiles one by one from the left side to the right side. Keep track of a special window that slides across the floor. The window has two sides. The right side moves forward every time a new tile is looked at. When a tile is already orange, everything is great and the window expands.
When the window hits a grey tile, the magical wand steps in to turn it orange. This uses up one of the precious charges of the wand. If there are still charges left, the window keeps growing. If the wand runs out of magic, the left side of the window has to slide forward until it finds the oldest grey tile that was changed. Doing this frees up a bit of magic so the window can keep moving ahead to find an even longer path.
Throughout this whole process, keep a constant watch on how wide the window is. Whenever the window gets larger than the previous best record, remember that new size. By the time the very last tile is checked, the record will show the longest possible line of orange tiles.
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 | Rust | TS | |||
| LeetcodeHelp | C++ | Python | Java | ||||||
| Progiez | C++ | Python | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fsq | C++ | ||||||||
| Garvit244 | Python | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fsq | C++ | ||||||||
| Garvit244 | Python | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ |
Videos
Similar Problems
- problem 487: Max Consecutive Ones II
- problem 1493: Longest Subarray of 1's After Deleting One Element
- problem 2511: Maximum Enemy Forts That Can Be Captured
Solved On The Same Day
- problem 643: Maximum Average Subarray I
- problem 1431: Kids With the Greatest Number of Candies
- problem 310: Minimum Height Trees
- problem 334: Increasing Triplet Subsequence
- problem 355: Design Twitter
- problem 368: Largest Divisible Subset
- problem 382: Linked List Random Node
- problem 398: Random Pick Index
- problem 1318: Minimum Flips to Make a OR b Equal to c
- problem 1679: Max Number of K-Sum Pairs
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