Problem Statement in English

You’re given an integer array nums and you can delete at most one element from it. Your task is to find the length of the longest subarray that can be obtained after deleting one element.


Approach

We can use a sliding window approach to solve this problem. The idea is to maintain a window that contains at most one zero. We will expand the window by moving the right pointer and contract it by moving the left pointer when we have more than one zero in the window.


Solution in Python


class Solution:
    def longestSubarray(self, nums: List[int]) -> int:
        l = 0
        res = 0
        diff = 0

        for r in range(len(nums)):
            diff += int(nums[r] == 0)

            while diff > 1 and l <= r:
                diff -= int(nums[l] == 0)
                l += 1

            res = max(res, r - l)

        return res

Complexity

  • Time: $O(n)$
    Since we iterate over the array once.

  • Space: $O(1)$
    We are using a constant amount of space.


And we are done.