Contiguous Array
mediumTime: O(n)Space: O(n)
Recognize the pattern
longest subarray with equal 0s and 1stransform 0→-1prefix sum = 0 means equal counts
Brute force idea
Check every subarray — O(n²).
Better approach
Replace 0s with -1s. Now equal 0s and 1s = sum 0. Prefix sum + hash map: same prefix at two positions = zero-sum between. O(n).
Key invariant
With 0→-1, equal counts ⟺ sum = 0. Same prefix sum at positions i,j means sum(i+1..j) = 0.
Watch out for
Not transforming 0s — without it, the problem is much harder. With it, it's standard prefix-sum-zero.