Longest Subarray of 1s After Deleting One Element

Delete one element from an array of 0s and 1s and find the longest run of 1s that is left.

Given an array nums that holds only 0s and 1s, delete exactly one element from it. Return the length of the longest subarray, a stretch of neighbouring elements, that holds only 1s in what is left. If no 1s are left, return 0.

Example 1
Input: nums = [1, 1, 0, 1]
Output: 3
Explanation: delete the 0 to get [1, 1, 1].
Example 2
Input: nums = [0, 1, 1, 1, 0, 1, 1, 0, 1]
Output: 5
Explanation: delete the 0 at index 4 to join [1, 1, 1] and [1, 1].
Example 3
Input: nums = [1, 1, 1]
Output: 2
Explanation: one element must be deleted, even if it is a 1.
Solution

The Idea

Picture a row of lights, some on and some off. A 1 is a light that is on, a 0 one that is off. You must take exactly one light out of the row, and the lights on either side close the gap. How long a run of lit lights can you end up with?

Take Example 2, [0, 1, 1, 1, 0, 1, 1, 0, 1]. It has three runs of 1s: three at indexes 1 to 3, two at indexes 5 and 6, and one at index 8. A single 0 sits between each pair of neighbouring runs.

Which element should go? Deleting the 0 at index 4 joins the run of three and the run of two into five 1s. Deleting the 0 at index 7 joins two and one into only three. Deleting a 1 never helps when a 0 could go instead. Example 3 has no 0 at all, so a 1 has to go, and three 1s become two.

Trying every element as the one to delete works, but it repeats a lot of scanning. Is there a way to see the answer directly? Look at where the five 1s of the best deletion came from: indexes 1 to 6 of the original array, a stretch that held exactly one 0. Look at the picture below.

The array 0, 1, 1, 1, 0, 1, 1, 0, 1 with a window from index 1 (left) to index 6 (right). The window holds 6 elements and one 0, at index 4. Deleting that 0 leaves 5 ones in a row.

The orange box marks that stretch. Such a stretch, with a left edge and a right edge, is called a window. The box is labelled "the window: 6 elements, one 0". Delete this 0, the dashed box at index 4, and the 6 elements become 5 ones in a row.

Any stretch that holds at most one 0 can be turned into a run of 1s with one deletion. If it holds one 0, delete the 0. If it holds none, delete a 1 at one end. Either way, the rest are all 1s, one fewer than the stretch had. So the question becomes: what is the longest stretch with at most one 0? The answer is its length minus 1.

Finding that stretch is a job for the sliding window technique: the right edge moves along the array one element at a time, and the left edge follows only when the window breaks the rule.

Solution Approach

Turning that idea into code means settling three things: how the window grows and shrinks, how to count the 0s inside it, and which length to report.

Growing and shrinking the window

Why not simply try deleting each element in turn? Each of the n choices needs a scan of the rest for the longest run of 1s, so that is about n² steps. For 10,000 elements, it is 100 million steps.

The window needs only one pass. right moves one step at a time and takes in a new element. If that element is a second 0, the window breaks the rule, so left moves forward until the earlier 0 has left the window.

Is it safe that left never moves back? Yes. Any window that ends at right and starts further left still holds both 0s, so it cannot be the answer. Later windows end further right and would hold both 0s too.

Counting the 0s in the window

How does the code know when the window holds two 0s? A counter, zeros, goes up by one when right takes in a 0, and down by one when left moves past a 0. The window must shrink exactly when zeros reaches 2.

The length to report

A window from left to right has right - left + 1 elements, and one of them is deleted. So the length of 1s it leaves is right - left. For [1, 1, 1] the window covers all three elements, and 3 - 1 = 2, which is Example 3, with no special case needed.

Reporting right - left + 1 instead answers a different question: how long a run you get if one 0 may be changed into a 1 rather than deleted. That version returns 4 for [1, 1, 0, 1] and 3 for [1, 1, 1], one too many each time.

Java Solution

The method longestSubarray works in these steps:

  1. First, set up the window: left starts at 0, zeros counts the 0s inside the window and starts at 0, and best holds the longest run found so far, also 0.
  2. A for loop moves right over the array, one index at a time. When nums[right] is 0, add one to zeros.
  3. Inside it, a while loop runs while zeros is more than 1. Each time, if nums[left] is 0, subtract one from zeros, then move left one step forward.
  4. Now the window holds at most one 0. Compare right - left with best and keep the larger.
  5. After right has passed the last element, return best, the longest run of 1s any window left behind.

The main method runs the three examples, an array of only 0s, an array with a single 1, and [1, 0, 0, 1, 1], where two 0s sit side by side.

Java
public class LongestSubarrayOf1sAfterDeletingOneElement {

    public static int longestSubarray(int[] nums) {
        int left = 0;
        int zeros = 0;                             // zeros in nums[left..right]
        int best = 0;
        for (int right = 0; right < nums.length; right++) {
            if (nums[right] == 0) {
                zeros++;
            }
            while (zeros > 1) {                    // two zeros: shrink from the left
                if (nums[left] == 0) {
                    zeros--;
                }
                left++;
            }
            best = Math.max(best, right - left);   // window size minus the deleted element
        }
        return best;
    }

    public static void main(String[] args) {
        System.out.println(longestSubarray(new int[] {1, 1, 0, 1}));
        System.out.println(longestSubarray(new int[] {0, 1, 1, 1, 0, 1, 1, 0, 1}));
        System.out.println(longestSubarray(new int[] {1, 1, 1}));
        System.out.println(longestSubarray(new int[] {0, 0, 0}));
        System.out.println(longestSubarray(new int[] {1}));
        System.out.println(longestSubarray(new int[] {1, 0, 0, 1, 1}));
    }
}

Running it prints:

Output
3
5
2
0
0
2

The 5 on the second line is the window from the picture, indexes 1 to 6, with its one 0 deleted. The 2 on the third line comes from [1, 1, 1]: the window covers all three elements, and right - left is 2.

The fourth line is 0 for [0, 0, 0]. As soon as right takes in the second 0, left moves up to it, so the window is a single 0 and right - left stays 0. The fifth line is 0 too, because [1] has one element and deleting it leaves nothing.

The last line comes from [1, 0, 0, 1, 1]. When right reaches the second 0, at index 2, left moves past the first 0 to index 2. The window then grows to indexes 2 to 4, holding 0, 1, 1, and 4 - 2 = 2.

Complexity

The work is the two edges of the window walking along the array, each only forward.

  • Time: O(n), because right visits each of the n elements once, and left never moves back, so the while loop moves it at most n times over the whole method.
  • Space: O(1), because the method keeps only left, right, zeros and best, however long the array is.

The same window, without the final subtraction, solves Max Consecutive Ones II, where the 0 is flipped instead of deleted.