Longest Subarray of 1's After Deleting One Element
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Sliding Window.
Longest Subarray of 1's After Deleting One Element
Given a binary array
nums, you must delete exactly one element. Return the maximum number of consecutive 1's remaining.Visual Representation
nums = [1, 1, 0, 1]
[1, 1, 0, 1]
^ Delete this 0
Remaining: [1, 1, 1] -> Len 3
Sliding Window Rule:
Window must contain at most ONE zero.
Final Result = WindowSize - 1Examples
Input: nums = [1,1,0,1]
Output: 3
Approach 1
Level I: Brute Force
Intuition
Iterate through every element in the array. For each element, assume it is the one being deleted, and then find the longest contiguous block of 1's that can be formed using the remaining elements.
Thought Process
- Iterate through each index
ifrom0ton-1. - Simulate deleting
nums[i]. - After 'deletion', find the longest sequence of 1's in the remaining array.
- Track the maximum length found across all possible deletions.
⏱ O(N^2)💾 O(N) to store the modified array, or O(1) if logic is careful.
Detailed Dry Run
| Deleting Index | Resulting Array | Max 1s | Result |
|---|---|---|---|
| 0 | [1, 0, 1] | 1 | 1 |
| 1 | [1, 0, 1] | 1 | 1 |
| 2 | [1, 1, 1] | 3 | 3 |
| 3 | [1, 1, 0] | 2 | 3 |
Approach 2
Level III: Optimal (Sliding Window)
Intuition
Thought Process
This is equivalent to 'Max Consecutive Ones III' with
k = 1. We find the longest window with at most one zero. Since we must delete one element, the result is always WindowSize - 1.Patterns
- Variable Window: Expand as long as zeros .
- Constraint: If
zeros > 1, shrink from left.
⏱ O(N)💾 O(1)
Detailed Dry Run
| R | Num | Zeros | Window Size | Result |
|---|---|---|---|---|
| 0 | 1 | 0 | 1 | 0 |
| 1 | 1 | 0 | 2 | 1 |
| 2 | 0 | 1 | 3 | 2 |
| 3 | 1 | 1 | 4 | 3 (MAX) |
⚠️ Common Pitfalls & Tips
If the array consists only of 1's, the result should be
N - 1, not N. Don't forget that one deletion is MANDATORY.Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.