This array problem gives you a binary array (containing only 0s and 1s). You are required to choose exactly one element to delete from the array. After the deletion, your goal is to find the maximum length of a contiguous subarray containing only 1s. Note that even if the array is made entirely of 1s, you must still delete one element.
This is a standard sliding window problem that tests a candidate's ability to manage state and constraints dynamically. Interviewers love it because it requires you to track an "allowance" (one 0 allowed in your block of 1s) and adjust your window size accordingly. It proves you can write linear-time algorithms instead of relying on brute-force checks.
The best approach is the Sliding Window (Two Pointers) pattern. You maintain a left pointer and a right pointer. As you iterate right through the array, you keep a count of how many 0s are in your current window. If the count of 0s exceeds 1, you shrink the window by moving the left pointer forward until the 0 count is back to 1. The length of the valid subarray of 1s is effectively the size of the window minus 1 (accounting for the deleted element).
Consider the array: [1, 1, 0, 1, 0, 1]
right at index 0 (1): Window [1]. Zeros = 0.right at index 1 (1): Window [1, 1]. Zeros = 0.right at index 2 (0): Window [1, 1, 0]. Zeros = 1. Valid!right at index 3 (1): Window [1, 1, 0, 1]. Zeros = 1. Valid! Max length of 1s = 4 - 1 = 3.right at index 4 (0): Window [1, 1, 0, 1, 0]. Zeros = 2. Invalid! We move left past the first 0. Window becomes [1, 0]. Zeros = 1.right at index 5 (1): Window [1, 0, 1]. Zeros = 1. Valid. Length = 3 - 1 = 2.
The maximum length is 3.A very common mistake is forgetting the edge case where the array contains no zeros (e.g., [1, 1, 1]). Candidates often return the full length of the array. However, the problem explicitly states you must delete one element. Therefore, if no zeros were found to act as the deleted element, you still must subtract 1 from the total length, returning 2.
When solving the Longest Subarray of 1's After Deleting One Element coding problem, remember that the length of the valid subarray is simply right - left. Because a standard window length is right - left + 1, and we are always "deleting" exactly one element, the + 1 and - 1 cancel out perfectly, resulting in a very clean mathematical formula for your max calculation.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Arithmetic Slices | Medium | Solve | |
| Longest Subarray of 1's After Deleting One Element | Medium | Solve | |
| Max Consecutive Ones II | Medium | Solve | |
| Longest Turbulent Subarray | Medium | Solve | |
| Maximum Sum of Two Non-Overlapping Subarrays | Medium | Solve |