Description: Given a binary array nums, you should delete one element from it. Return the size of the longest non-empty subarray containing only 1’s in the resulting array. Return 0 if there is no such subarray.

Code:

def longestSubarray(self, nums: List[int]) -> int:
        left = zero_count = max_len = 0
        for right in range(len(nums)):
            if nums[right] == 0:
                zero_count += 1
                
            # If more than one zero, shrink the window    
            while zero_count > 1:
                if nums[left] == 0:
                    zero_count -= 1
                left += 1
                
            # Update max length — subtract 1 to simulate required deletion 
            # max_len = max(max_len, right - left + 1 - 1)
            max_len = max(max_len, right - left)
        
        return max_len
            

Efficiency:

Time Complexity: O(n)

Space Complexity: O(1)

Test:

# --- Inline assert tests ---
assert longestSubarray([1,1,0,1]) == 3  # After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.  
assert longestSubarray([0,1,1,1,0,1,1,0,1]) == 5  # After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1].  
assert longestSubarray([1,1,1]) == 2  # You must delete one element.