AAlgoLoopSpaced repetition for LeetCode
MEDIUMSliding WindowLeetCode ↗

Longest Subarray of 1's After Deleting One Element

The key idea

You must delete exactly one element, so the answer is the longest window that contains at most ONE zero, minus one for the deleted slot. Slide a window that allows a single zero; when a second zero enters, shrink from the left until only one zero remains.

Problem

Given a binary array nums, you should delete one element from it.

Return the size of the longest non-empty subarray containing only 1's in the resulting array. Return 0 if there is no such subarray.

Constraints

Examples

Input: nums = [1,1,0,1] Output: 3
Input: nums = [0,1,1,1,0,1,1,0,1] Output: 5
Input: nums = [1,1,1] Output: 2

Complexity

Time: O(n) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More Sliding Window problems