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).
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- Time: O(n)
- Space: O(1)