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 ElementInput: [1,1,0,1]1101Delete this 0Result: [1,1,1]111Longest subarray length: 3
Understanding the Visualization
1
Input Array
Binary array with 0's and 1's: [1,1,0,1]
2
Delete Element
Remove one element (must delete exactly one)
3
Find Longest
Find longest contiguous subarray of 1's: length 3
Key Takeaway
🎯 Key Insight: Find the longest subarray containing at most one 0, then subtract 1
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