Longest Subarray of 1's After Deleting One Element
Difficulty: Medium · Pattern: Sliding Window · LeetCode #1493
Delete exactly one element from the binary array nums. Return the length of the longest non-empty subarray containing only 1s in the result (0 if there is none).
Examples
text
[1, 1, 0, 1] → 3
[0, 1, 1, 1, 0, 1, 1, 0, 1] → 5
[1, 1, 1] → 2 (must delete one)Hints
- Find the longest window with at most one zero; the deleted element is that zero (or any one element if there's none).
- The answer is the window length minus 1.
Approach
Same template as Max Consecutive Ones III with k = 1: maintain a window containing at most one zero, and record r − l (window length − 1, since one element is deleted). Deleting is mandatory, which is why an all-ones array of length n gives n − 1.
Complexity
Time: O(n). Space: O(1).
Python solution
def longestSubarray(nums):
l = zeros = best = 0
for r, x in enumerate(nums):
zeros += x == 0
while zeros > 1:
zeros -= nums[l] == 0
l += 1
best = max(best, r - l)
return bestJavaScript solution
function longestSubarray(nums) {
let l = 0, zeros = 0, best = 0;
for (let r = 0; r < nums.length; r++) {
if (nums[r] === 0) zeros++;
while (zeros > 1) { if (nums[l] === 0) zeros--; l++; }
best = Math.max(best, r - l);
}
return best;
}