Home
DSA Patterns
Sliding Window
Longest Subarray of 1's After Deleting One Element
Longest Subarray of 1's After Deleting One Element
Find the longest subarray of 1s left after deleting exactly one element, using a sliding window that allows at most one zero inside it.
Problem Understanding
Longest Subarray of 1's After Deleting One Element (LeetCode 1493): given a binary array nums, delete exactly one element and return the length of the longest non-empty subarray containing only 1s in the result. Return 0 if there is none.
Examples: [1, 1, 0, 1] → 3; [0, 1, 1, 1, 0, 1, 1, 0, 1] → 5; [1, 1, 1] → 2.
The Intuition: A Window That Tolerates One Zero
After deleting one element, a run of 1s in the result came from a stretch of the original with at most one zero, the one you deleted.
- Grow the window to the right.
- Shrink from the left whenever it holds a second zero.
- Measure length - 1, the 1s left after the deletion.
It is Max Consecutive Ones III with k = 1, counting the deletion.
Interactive Walkthrough
AT MOST ONE ZERO IN THE WINDOW
GROW RIGHT
nums (window outlined)
lo hi
0
1
2
3
4
5
6
7
8
zeros
1
length − 1
0
best
0
nums[0] = 0 joins the window. Zeros in it: 1
Next
Window [0, 0] has 1 elements; deleting one leaves 0
nums
The outlined cells are the window, and a zero inside it is tinted: that is the element to delete. Try All ones to see why the answer is n - 1.
Dry Run Table
Input: [0, 1, 1, 1, 0, 1, 1, 0, 1].
| hi | Window | zeros | length − 1 | best |
|---|---|---|---|---|
| 0 to 3 | [0, 3] | 1 | 3 | 3 |
| 4 | [1, 4] after shrinking | 1 | 3 | 3 |
| 5 | [1, 5] | 1 | 4 | 4 |
| 6 | [1, 6] | 1 | 5 | 5 |
| 7 | [5, 7] after shrinking | 1 | 2 | 5 |
| 8 | [5, 8] | 1 | 3 | 5 |
Answer: 5, from the window [1, 6] with the zero at index 4 deleted.
The Solution Template
A variable-size window with a zero counter; the answer is the largest hi - lo.
Longest Subarray of 1's After Deleting One Element Code
1var longestSubarray = function(nums) {2 let lo = 0, zeros = 0, best = 0;3 for (let hi = 0; hi < nums.length; hi++) {4 if (nums[hi] === 0) zeros++;5 while (zeros > 1) {6 if (nums[lo] === 0) zeros--;7 lo++;8 }9 best = Math.max(best, hi - lo);10 }11 return best;12};
Edge Cases & Common Mistakes
- All ones: answer n - 1, because the deletion is mandatory.
- All zeros: answer 0.
- Returning the window length: forgets the deleted element; use hi - lo, not hi - lo + 1.
- Shrinking with if instead of while: works here because zeros rises by at most 1 per step, but while is the safe general form.
Summary
Slide a window that holds at most one zero and record its length minus one. O(n) time, O(1) space.
More practice: DSA interview questions with answers · patterns cheat sheet
