SDE & MLE Prep

525. Contiguous Array

Problem

Given a binary array nums, return the length of the longest contiguous subarray containing equally many 0s and 1s.

Example: [0,1,1,0,1,1] → 4 ([0,1,1,0])

Constraints: n ≤ 10⁵.

Treat 0 as −1. A subarray with equal 0s and 1s has sum 0 ⇔ two equal prefix sums. Store the first index of each prefix; the longest span between equal prefixes wins.

nums   0   1   1   0   1   1
as±1  -1  +1  +1  -1  +1  +1
pre  0 -1   0   1   0   1   2      pre=0 first at -1, again at idx 3 -> len 4

Complexity: O(n) time, O(n) space.

class Solution:
    def findMaxLength(self, nums: List[int]) -> int:
        first = {0: -1}
        pre = best = 0
        for i, x in enumerate(nums):
            pre += 1 if x else -1
            if pre in first:
                best = max(best, i - first[pre])
            else:
                first[pre] = i
        return best