Skip to content
Problem 1493 · LeetCode 1493(opens in a new tab)

Longest Subarray of 1's After Deleting One Element

MediumArrays

You are given an array nums made only of 0s and 1s. You must remove exactly one element from it, whatever its value.

After the removal, find the longest stretch of neighbouring elements that are all 1, and return its length. If no 1 is left, return 0.

Example 1

Input:  nums = [1, 1, 0, 1, 1, 1, 0, 1]
Output: 5
Why:    remove index 2 and the runs of 2 and 3 join
2 more examples and the constraints

Example 2

Input:  nums = [1, 1, 1, 1]
Output: 3
Why:    one element must go, even if it is a 1

Example 3

Input:  nums = [0, 0, 0]
Output: 0
Why:    there is no 1 to keep

Constraints

  • 1 ≤ length of nums ≤ 100,000
  • Every nums[i] is 0 or 1

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Try every deletionO(n²)
  2. Runs on each sideO(n)
  3. Sliding window, one zero allowedO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 numbersVerdict
Try every deletionO(n²)
Clear, but times out
Runs on each sideO(n)
Passes; two extra arrays
Sliding window, one zero allowedO(n)
Best; one pass, O(1) space

n = the length of nums.

Edge cases to test

  • No zeros. [1, 1, 1, 1] gives 3: a 1 still has to be deleted.
  • No ones. [0, 0, 0] gives 0.
  • A single element. [1] and [0] both give 0, since the array becomes empty.
  • Two zeros in a row. [1, 0, 0, 1] gives 1: deleting one zero cannot join the two 1s.

Common mistakes

  • Returning the window size right - left + 1, which forgets the deleted element and gives n for all 1s.
  • Only trying to delete zeros, then returning n when the array has none.
  • Resetting left straight to right on a second zero, which throws away the 1s after the first zero.

How to talk through it

  1. 1Clarify. Must I delete exactly one element even when the array is all 1s? What do I return when there are no 1s?
  2. 2Give the brute force. Try deleting each index and rescan for the longest run: O(n²).
  3. 3Reframe it. The answer is the longest window with at most one zero, minus one for the deletion.
  4. 4Code the window. Grow right, count zeros, shrink left while there are two, record right - left.
  5. 5Test out loud. Run all 1s, all 0s, a single element and two zeros side by side.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?