Problem
You are given a binary array (containing only 0s and 1s). You must delete exactly one element โ your choice of which index. Return the length of the longest contiguous subarray of all 1s that remains after the deletion.
- Input:
nums = [1, 1, 1, 0, 1, 1, 1, 1, 1] - Output:
8 - Explanation: Deleting the 0 at index 3 leaves eight consecutive 1s.
Note that if the array contains no zeros (e.g., [1, 1, 1]), you still must delete one element, so the best you can achieve is n โ 1 = 2.
Intuition
Think of the problem as finding the longest window that contains at most one zero โ deleting that zero yields a run of 1s equal to the window size minus one. A sliding window keeps the window valid by advancing the left boundary whenever a second zero enters. Because the deletion is mandatory, the answer is always window_size โ 1 (right โ left), even when the window holds no zeros at all.
Approach 1 โ Brute Force
For each index, skip that element and count the longest run of 1s in the remaining sequence.
- For every index
skipfrom 0 to nโ1, treat it as the deleted position. - Scan the full array, accumulating a run of consecutive 1s but treating
skipas absent. - Reset the run count when a 0 that wasn't deleted is encountered.
- Track the global maximum across all candidate deletions.
1def longestSubarray(self, nums: list[int]) -> int:
2 max_length = 0
3 for skip in range(len(nums)):
4 current_run = 0
5 for i, value in enumerate(nums):
6 if i == skip:
7 continue # treat this index as deleted
8 if value == 1:
9 current_run += 1
10 max_length = max(max_length, current_run)
11 else:
12 current_run = 0 # undeleted zero resets the run
13 return max_lengthTime: O(nยฒ) โ each of the n candidate deletions triggers a full O(n) scan.
Space: O(1) โ only counters; no extra data structures.
Approach 2 โ Sliding Window
Maintain a window [left, right] that contains at most one zero. The answer for any valid window is right โ left โ that's the window size minus the one element we always delete.
- Initialize
left = 0andzero_count = 0. - Advance
rightone step at a time; ifnums[right] == 0, incrementzero_count. - While
zero_count > 1, shrink from the left: ifnums[left] == 0, decrementzero_count; then advanceleft. - Record
right โ leftas a candidate answer (one element from the window is always deleted). - Return the maximum recorded value.
1def longestSubarray(self, nums: list[int]) -> int:
2 left = 0
3 zero_count = 0
4 max_length = 0
5 for right in range(len(nums)):
6 if nums[right] == 0:
7 zero_count += 1
8 # Shrink until the window holds at most one zero
9 while zero_count > 1:
10 if nums[left] == 0:
11 zero_count -= 1
12 left += 1
13 # right - left = window size minus the one mandatory deletion
14 max_length = max(max_length, right - left)
15 return max_lengthTime: O(n) โ each element enters and exits the window at most once.
Space: O(1) โ only two pointers and a zero counter.
Complexity Summary
| Approach | Time | Space | When to use |
|---|---|---|---|
| Brute Force | O(nยฒ) | O(1) | Verifying correctness on tiny inputs |
| Sliding Window | O(n) | O(1) | Always โ linear time is achievable here |
Common Mistakes
- Using
right โ left + 1instead ofright โ leftโ the window size includes the one element being deleted; forgetting to subtract 1 overcounts by one for every window. - Skipping the deletion on all-ones arrays โ the problem requires deleting exactly one element regardless; returning
nfor[1, 1, 1]is wrong.right โ leftnaturally yieldsn โ 1here. - Advancing
leftwithifinstead ofwhileโ when consecutive zeros appear (e.g.,[1, 0, 0, 1]), a singleifleaves two zeros in the window after moving left once. - Not updating
zero_countwhen shrinking โ incrementingleftwithout checkingnums[left]corrupts the zero count, allowing invalid windows with more than one zero. - Treating
nums[right] == 1as the only update โ the zero count must be incremented onnums[right] == 0, not conditionally updated at the end of the loop; misplacing that check causes the window constraint to lag by one step.
Related Problems
Max Consecutive Ones IIIโ direct generalization allowing up to k zeros in the window instead of exactly oneLongest Repeating Character Replacementโ same sliding window skeleton but the constraint is on a character replacement budgetMinimum Window Substringโ harder sliding window that tracks full character frequency maps inside the windowLongest Substring Without Repeating Charactersโ sliding window that shrinks on a uniqueness violation; same structural patternContiguous Arrayโ finds the longest subarray with equal 0s and 1s; shares the intuition of tracking zero counts to identify valid subarrays