Longest Subarray of 1's After Deleting One Element - 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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,1,0,1]
Output: 3
💡 Note: After deleting the element at index 2, we get [1,1,1] which has the longest subarray of 1's with length 3.
Example 2 — All Ones
$ Input: nums = [0,1,1,1,0,1,1,0,1]
Output: 5
💡 Note: After deleting the element at index 4, we get [0,1,1,1,1,1,0,1] and the longest subarray of 1's is [1,1,1,1,1] with length 5.
Example 3 — All Zeros
$ Input: nums = [1,1,1]
Output: 2
💡 Note: We must delete one element, so after deleting any element we get [1,1] with length 2.

Constraints

  • 1 ≤ nums.length ≤ 105
  • nums[i] is either 0 or 1

Visualization

Tap to expand
Longest Subarray of 1's After Deleting One Element INPUT Binary Array nums: 0 1 2 3 1 1 0 1 = 1 (ones) = 0 (zero) Input Parameters: nums = [1,1,0,1] length = 4 Goal: Delete ONE element, find longest subarray of 1's ALGORITHM STEPS 1 Sliding Window Use two pointers (left, right) 2 Count Zeros Track zeros in window (max 1) 3 Shrink if Needed Move left when zeros > 1 4 Track Maximum max = window_size - 1 Window Expansion: 1 1 0 1 window (all 4) zeros=1, window=4 result = 4 - 1 = 3 FINAL RESULT After deleting the 0: 1 1 1 OUTPUT 3 Longest subarray of 1's after deleting one element Verification: [1,1,0,1] --> delete 0 [1,1,1] = 3 ones -- OK Key Insight: The sliding window maintains at most ONE zero inside. When we find a valid window, the answer is (window_size - 1) because we MUST delete one element. This handles both cases: deleting the zero to merge 1's, or deleting a 1 if the array is all 1's. TutorialsPoint - Longest Subarray of 1's After Deleting One Element | Optimal Solution (Sliding Window) O(n) Time | O(1) Space
Asked in
Facebook 45 Amazon 38 Google 32 Microsoft 28
78.0K Views
High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen