1004. Max Consecutive Ones III
Quick Identifier
- Topic: sliding-window
- Pattern: Variable Window with Limited Flips (Need/Have + budget)
- Hint: You can flip at most
kzeros to1. Use a sliding window that tracks the number of zeros in the current window; when it exceedsk, shrink from the left. - Difficulty: Medium
- Companies: Amazon, Google, Meta, Microsoft, Facebook
- LeetCode: 1004
Quick Sights
- Time Complexity:
O(n)– each index is visited at most twice (once by the right pointer, once by the left pointer). - Space Complexity:
O(1)– only a few integer counters are needed. - Core Mechanism: Maintain a window
[left, right]and a count of zeros inside it. Expandright; if zeros >k, moveleftforward until zeros ≤k. The window length is the candidate answer.
Concept Explanation
Think of the binary array as a road with potholes (0). You have a limited number of repair kits (k). The goal is to drive as far as possible without running out of kits.
- Expansion – drive forward (
right) and count encountered potholes. - Budget Check – if potholes exceed
k, you must backtrack (left) and start repairing the leftmost potholes (effectively “un‑use” those repair kits) until the budget is satisfied again. - Recording – the longest stretch you successfully drove with ≤
krepairs is the answer.
Diagram
Loading diagram…
Study Pattern (SDE3+)
- 0‑3 min: Explain the “repair‑kit budget” analogy and why a variable‑size window is appropriate.
- Implementation pass: Emphasise the
zeroscounter and thewhile zeros > kloop that movesleft. - 5 min extension: Discuss how to adapt the approach if the input were a stream of bits (online algorithm) – you would still keep the same counters.
Approaches
- Brute force – examine all O(n²) subarrays and count zeros – too slow.
- Prefix‑sum + binary search – could work but adds O(n log n) complexity.
- Optimal – sliding window with zero‑budget –
O(n)time,O(1)space. (Always pick this)
Optimal Solution
Go
func longestOnes(nums []int, k int) int {
left, zeros, best := 0, 0, 0
for right, val := range nums {
if val == 0 {
zeros++
}
for zeros > k {
if nums[left] == 0 {
zeros--
}
left++
}
if length := right - left + 1; length > best {
best = length
}
}
return best
}JavaScript
function longestOnes(nums, k) {
let left = 0, zeros = 0, best = 0;
for (let right = 0; right < nums.length; right++) {
if (nums[right] === 0) zeros++;
while (zeros > k) {
if (nums[left] === 0) zeros--;
left++;
}
best = Math.max(best, right - left + 1);
}
return best;
}Walkthrough
Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2
- Expand until index 5 → zeros = 3 > k, shrink left until zeros = 2 (left moves to index 2).
- Continue expanding; the longest valid window found is length 6 (
[0,1,1,1,1,0]after appropriate shifts).
Edge Cases
k>= total zeros → answer islen(nums).- All ones → answer is
len(nums). - All zeros with
k = 0→ answer is0.
Pitfalls
- Forgetting to decrement
zeroswhen movingleftpast a zero. - Using
>= kinstead of> kin the while condition, which would incorrectly shrink the window.
Similar Problems
- [3. Longest Substring Without Repeating Characters] – variable window with distinct count.
- [209. Minimum Size Subarray Sum] – variable window with sum ≥ target.
- [239. Sliding Window Maximum] – different pattern (monotonic deque).
Mind‑Map Tags
#sliding-window #variable-window #budget #zero‑flip #medium
Mark this page when you finish learning it.
Last updated on
Spotted something unclear or wrong on this page?