Max Consecutive Ones III solution explained
Max Consecutive Ones III gives you a list of 0s and 1s and a budget k, and asks for the longest run of 1s you can create by turning at most k zeros into ones. Read it as the longest stretch that contains no more than k zeros: grow a window to the right, and when it holds k + 1 zeros, advance the left edge past one zero. Each index enters and leaves the window once, so the answer takes O(n) time and O(1) extra space.
By Evin JohnPublished 8 min read
Problem statement in our words
You have a list where every entry is 0 or 1, plus a non-negative integer k. You may change up to k of the zeros into ones. After those changes, what is the longest run of consecutive ones the list can contain? You only return the length, not which zeros you changed.
bits = [1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1]
k = 0 -> 3 the existing run 1 1 1 at positions 6 to 8
k = 1 -> 5 flip position 9: positions 6 to 10 become 1 1 1 1 1
k = 2 -> 7 flip positions 4 and 5: positions 2 to 8 become all 1sTry to find the k = 1 answer by deciding which zero to flip, and you will notice how awkward that is: flipping position 1, 4 or 5 each looks promising until you count. That awkwardness is the hint. Stop choosing flips and look at windows instead: any window with at most k zeros can be turned into all ones, and any run of ones you can create is such a window. So the answer is the length of the longest window holding at most k zeros.
Why interviewers use it
It is a short problem with a clear right answer, which makes it good for checking whether you know the variable-size window well enough to write it without bugs. It also has a natural progression: quadratic, then n log n with prefix sums and binary search, then linear. Candidates who jump straight to the window are often asked why it is correct, so be ready to say why moving the left edge forward never skips the best answer.
Starting slow
def longest_ones_slow(bits, k):
best = 0
for start in range(len(bits)):
zeros = 0
for end in range(start, len(bits)):
zeros += bits[end] == 0
if zeros > k:
break
best = max(best, end - start + 1)
return bestA middle step: prefix counts and binary search
Build a list where entry i is the number of zeros before position i. The zeros inside any window are then a subtraction of two entries, and because the list never decreases, the farthest end for each start can be found with binary search. This is O(n log n) and it is worth knowing, because it still works when the question changes to many queries with different budgets over the same list.
from bisect import bisect_right
def longest_ones_binary_search(bits, k):
zeros_before = [0]
for b in bits:
zeros_before.append(zeros_before[-1] + (b == 0))
best = 0
for start in range(len(bits)):
# last j with zeros_before[j] - zeros_before[start] <= k; the window is start..j-1
j = bisect_right(zeros_before, zeros_before[start] + k) - 1
best = max(best, j - start)
return bestThe linear window
Keep two pointers and a count of zeros between them. Move the right pointer forward one step at a time, adding to the count when it passes a zero. If the count goes over k, move the left pointer forward until one zero has left the window. Now the window is valid again, and its length is a candidate. Why is it safe to move the left pointer and never come back? Any window that starts at the old left position and ends further right contains at least as many zeros as the current one, so it is invalid too and cannot be the answer.
def longest_ones(bits, k):
left = zeros = best = 0
for right, b in enumerate(bits):
if b == 0:
zeros += 1
while zeros > k:
if bits[left] == 0:
zeros -= 1
left += 1
best = max(best, right - left + 1)
return bestThe window that only grows
There is a shorter version worth recognizing. Instead of shrinking until the window is valid, move the left pointer by exactly one whenever the window is over budget. The window's size then never decreases: it either grows by one or slides along unchanged. Its size at the end equals the largest valid window ever seen, so the answer is the list length minus the final left position, and no running maximum is needed.
function longestOnes(bits, k) {
let left = 0;
let zeros = 0;
for (let right = 0; right < bits.length; right++) {
if (bits[right] === 0) zeros++;
if (zeros > k) {
if (bits[left] === 0) zeros--;
left++;
}
}
return bits.length - left;
}While the window slides over budget, the count can stay above k for a while, so the window is not always valid in the middle of the loop. That is fine, because the window only grows again once enough zeros have left. Be ready to explain this if you use it; the shrinking version is easier to defend if you are unsure.
Cost comparison
| Approach | Time | Extra space |
|---|---|---|
| Extend from every start | O(n²) | O(1) |
| Prefix zero counts + binary search | O(n log n) | O(n) |
| Shrinking sliding window | O(n) | O(1) |
| Non-shrinking sliding window | O(n) | O(1) |
Edge cases
- k = 0: the longest run of ones already in the list, the plain version of this problem.
- k at least the number of zeros: the whole list.
- All zeros: the answer is min(k, n).
- All ones: n, whatever k is.
- An empty list: 0.
Pitfalls
- Trying to choose which zeros to flip, often greedily by the longest neighboring runs, which fails on many lists.
- Shrinking with if instead of while and still tracking a running maximum, which can record the length of a window that is over budget.
- Decreasing the zero count when the left pointer passes a 1.
- Using right - left instead of right - left + 1 for the window length.
- Answering with the number of flips used instead of the run length.
Follow-ups you may hear
- Exactly one flip allowed: set k = 1; some interviewers ask for this first as a warm-up.
- The bits arrive as a stream that does not fit in memory: you cannot look back at the left pointer's bit. Keep a queue of the positions of the last k + 1 zeros, and when a new zero arrives over budget, the window starts just after the oldest one.
- Return the positions to flip: record the window's bounds when the best length is updated, then list the zeros inside it.
- Many budgets over one list: build the prefix counts once and answer each budget with the binary search pass, or precompute answers for every k.
Explaining your thinking
Fictional example
- Candidate
- Choosing which zeros to flip gets complicated fast, so I will flip the question: any stretch with at most k zeros can become all ones, so I want the longest such stretch.
- Candidate
- I will keep a window and a count of zeros in it. The right edge always moves forward. When I go over k, I move the left edge until one zero leaves.
- Interviewer
- How do you know you never need the left edge to move back?
- Candidate
- Any window starting further left that ends here or later contains at least the same zeros, so it is already over budget. Each pointer moves at most n times, so it is linear with constant space.
Related problems
Fruit Into Baskets runs the same window with a limit on distinct values instead of a budget of zeros, and Longest Substring Without Repeating Characters shrinks on a repeated character. Sliding Window Median shows what happens when the window has a fixed size but needs ordered data. The string version of this budget idea, replacing up to k characters to make the longest uniform run, is a natural next problem. For a change of pattern, Longest Palindrome is solved with counts alone.
Practice support from Natively
Interviewers often press on why the left pointer never moves back, and that answer is easier to give if you have said it before. With Natively on Mac or Windows, a mock round can start from a screenshot of the problem; it can suggest the reframing to a window with at most k zeros and transcribe your explanation for review afterwards. Read more on the LeetCode AI helper page.
Questions people ask
How do you solve Max Consecutive Ones III?
Find the longest window with at most k zeros. Move the right pointer forward and count zeros; when the count exceeds k, move the left pointer until one zero leaves. Track the largest window length.
Why does a sliding window work for Max Consecutive Ones III?
Any window with at most k zeros can be flipped into all ones, and any window starting further left that ends at the same place or later has at least as many zeros, so the left pointer never needs to move back.
What is the time and space complexity of Max Consecutive Ones III?
O(n) time and O(1) extra space with the sliding window. Prefix counts with binary search give O(n log n), and extending from every start is O(n squared).
What is the non-shrinking window trick?
Move the left pointer by only one step whenever the window is over budget. The window never gets smaller, so its final size, the list length minus the left pointer, equals the best valid window seen.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
