Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created August 24, 2025 22:40
Show Gist options
  • Select an option

  • Save Ifihan/1acec4322cd2dd02ad56def5cd59acb4 to your computer and use it in GitHub Desktop.

Select an option

Save Ifihan/1acec4322cd2dd02ad56def5cd59acb4 to your computer and use it in GitHub Desktop.
Longest Subarray of 1's After Deleting One Element

Question

Approach

I use a sliding window that allows at most one zero inside it—because I can delete one element. I expand the right pointer over the array, counting zeros in the current window. If the zero count exceeds one, I move the left pointer forward and decrement the zero count when I pass a zero. For each step I record the window length; since I must delete one element, the best achievable all-ones subarray length for the current window is window_len - 1. Taking the maximum over all windows gives the answer. This naturally handles edge cases like “all ones” (I must delete one, so length reduces by 1) and “all zeros” (answer becomes 0).

Implementation

class Solution:
    def longestSubarray(self, nums: List[int]) -> int:
        left = 0
        zeros = 0
        best = 0

        for right, x in enumerate(nums):
            if x == 0:
                zeros += 1

            while zeros > 1:
                if nums[left] == 0:
                    zeros -= 1
                left += 1

            best = max(best, right - left + 1)

        return best - 1 if best > 0 else 0

Complexities

  • Time: O(n)
  • Space: O(1)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment