Longest Subarray of 1s After Deleting One Element
Given a binary array nums, you must delete exactly one element from it. Return the length of the longest subarray of only 1s in the remaining array . Find the longest window that contains at most one 0, then subtract one for the element the window is forced to delete — even a window with no zero must give one up.
Constraints
- 1 ≤ nums.length ≤ 105
- numsi is either 0 or 1
Example
nums = [1, 1, 0, 1]3Explanation Delete the 0 at index 2 to leave [1, 1, 1], a run of length 3.
Longest window with at most one 0, minus one
Window [1,1] has zero zeros; best window length = 2.
What happens in this step
right=1: nums[1]=1 → zeros stays 0 0 > 1? no → no shrinking needed window length = right - left + 1 = 1 - 0 + 1 = 2 best = max(1, 2) = 2
Steps to visualize
- Grow right and count zeros inside the window.
- While the window holds more than one zero, shrink from the left.
- Track the longest window length seen, regardless of whether it holds a zero.
- Every window still needs one element removed, even an all-ones window.
- Subtract one from the longest window length for the final answer.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
Window [1,1] has zero zeros; best window length = 2.
What happens in this step
right=1: nums[1]=1 → zeros stays 0 0 > 1? no → no shrinking needed window length = right - left + 1 = 1 - 0 + 1 = 2 best = max(1, 2) = 2
Solution
function longestSubarray(nums) {
let left = 0;
let zeros = 0;
let best = 0;
for (let right = 0; right < nums.length; right++) {
if (nums[right] === 0) zeros++;
while (zeros > 1) {
if (nums[left] === 0) zeros--;
left++;
}
best = Math.max(best, right - left + 1);
}
return best - 1;
}- Time
- O(n)
- Space
- O(1)
Test cases
| Input | Expected | Covers |
|---|---|---|
nums = [1, 1, 0, 1] | 3 | Docstring example |
nums = [1, 1, 1] | 2 | All 1s — one must still be deleted |
nums = [0, 0, 0] | 0 | All 0s |
nums = [1] | 0 | Single element must be deleted, leaving nothing |
nums = [0] | 0 | Single zero element |
nums = [1, 0, 0, 1] | 1 | Two zeros force the shortest valid window |
nums = [0, 1, 1, 1, 0, 1, 1, 0, 1] | 5 | Classic walkthrough array with scattered zeros |