medium

Longest Subarray of 1s After Deleting One Element

Delete exactly one element and find the longest run of 1s left in the array.

1. Define the problem

Longest Subarray of 1s After Deleting One Element

Given a binary array nums, you must delete exactly one element from it. Return the length of the longest subarray of only 1s in the remaining array . Find the longest window that contains at most one 0, then subtract one for the element the window is forced to delete — even a window with no zero must give one up.

Constraints

  • 1 ≤ nums.length ≤ 105
  • numsi is either 0 or 1

Example

Inputnums = [1, 1, 0, 1]
Output3

Explanation Delete the 0 at index 2 to leave [1, 1, 1], a run of length 3.

2. Visualize the solution

Longest window with at most one 0, minus one

Longest window with at most one 0, minus one
Statusvalid

Window [1,1] has zero zeros; best window length = 2.

What happens in this step

right=1: nums[1]=1 → zeros stays 0
  0 > 1? no → no shrinking needed
  window length = right - left + 1 = 1 - 0 + 1 = 2
  best = max(1, 2) = 2
Step 1 of 3

Steps to visualize

  1. Grow right and count zeros inside the window.
  2. While the window holds more than one zero, shrink from the left.
  3. Track the longest window length seen, regardless of whether it holds a zero.
  4. Every window still needs one element removed, even an all-ones window.
  5. Subtract one from the longest window length for the final answer.
3. Walk through the code

Walk through the code

Same walkthrough, now with the code. Press Next to move one step and watch which lines run.

Longest window with at most one 0, minus one
Statusvalid

Window [1,1] has zero zeros; best window length = 2.

What happens in this step

right=1: nums[1]=1 → zeros stays 0
  0 > 1? no → no shrinking needed
  window length = right - left + 1 = 1 - 0 + 1 = 2
  best = max(1, 2) = 2
Step 1 of 3
4. Solution

Solution

solution.tsTypeScript
function longestSubarray(nums) {
  let left = 0;
  let zeros = 0;
  let best = 0;

  for (let right = 0; right < nums.length; right++) {
    if (nums[right] === 0) zeros++;

    while (zeros > 1) {
      if (nums[left] === 0) zeros--;
      left++;
    }

    best = Math.max(best, right - left + 1);
  }

  return best - 1;
}
Time
O(n)
Space
O(1)
5. Test cases

Test cases

InputExpectedCovers
nums = [1, 1, 0, 1]3Docstring example
nums = [1, 1, 1]2All 1s — one must still be deleted
nums = [0, 0, 0]0All 0s
nums = [1]0Single element must be deleted, leaving nothing
nums = [0]0Single zero element
nums = [1, 0, 0, 1]1Two zeros force the shortest valid window
nums = [0, 1, 1, 1, 0, 1, 1, 0, 1]5Classic walkthrough array with scattered zeros