Longest Subarray of 1's After Deleting One Element - Problem

Given a binary array nums containing only 0s and 1s, you must delete exactly one element from it.

Your task is to return the maximum length of the longest contiguous subarray containing only 1s after deleting one element. If no such subarray exists, return 0.

Key Points:

  • You must delete exactly one element (cannot skip deletion)
  • The resulting subarray must contain only 1s
  • Return the length of the longest such subarray

Example: In array [1,1,0,1], if we delete the 0 at index 2, we get [1,1,1] with length 3.

Input & Output

example_1.py โ€” Basic case
$ Input: [1,1,0,1]
โ€บ Output: 3
๐Ÿ’ก Note: After deleting the 0 at index 2, we get [1,1,1] which has length 3.
example_2.py โ€” Multiple zeros
$ Input: [0,1,1,1,0,1,1,0,1]
โ€บ Output: 5
๐Ÿ’ก Note: We can delete one of the zeros to connect sequences. Deleting the 0 at index 4 gives us a subarray [1,1,1,1,1] of length 5.
example_3.py โ€” All ones
$ Input: [1,1,1,1]
โ€บ Output: 3
๐Ÿ’ก Note: Since we must delete exactly one element, we delete any 1 and get length 3.

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • nums[i] is either 0 or 1
  • You must delete exactly one element

Visualization

Tap to expand
Sliding Window: Pearl Necklace AnalogyNecklace: [1,1,0,1,1,0,1] (White=1, Black=0)Measuring Tape (Window): Can span at most 1 black beadWindow Length = 5โœ—LRAfter removing the black bead: Length = 4Longest sequence of white pearls!๐ŸŽฏ Key Insight: Sliding Window MagicWindow with โ‰ค1 zero โ†’ Delete that zero โ†’ All 1s subarray!
Understanding the Visualization
1
Start measurement
Place the measuring tape at the beginning of the necklace
2
Expand the tape
Stretch the tape to include more pearls, counting any black beads
3
Adjust when needed
If the tape spans more than one black bead, shrink it from the left
4
Record maximum
Track the longest stretch that spans at most one black bead
Key Takeaway
๐ŸŽฏ Key Insight: By maintaining a sliding window with at most one zero, we efficiently find the longest possible subarray of 1s after mandatory deletion - the window size minus one gives us our answer!
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
52.3K Views
Medium-High Frequency
~15 min Avg. Time
1.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