525. Contiguous Array
Asked at 14Meta47Amazon47Bloomberg39Google38Microsoft33Cisco37Akamai86Morgan Stanley54Oracle49Accenture44Walmart Labs43TikTok35Infosys30tcs27
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
assert Solution().findMaxLength([0, 1]) == 2
assert Solution().findMaxLength([0, 1, 1, 0, 1, 1]) == 4
class Solution {
public int findMaxLength(int[] nums) {
Map<Integer, Integer> first = new HashMap<>();
first.put(0, -1);
int pre = 0, best = 0;
for (int i = 0; i < nums.length; i++) {
pre += nums[i] == 1 ? 1 : -1;
Integer j = first.putIfAbsent(pre, i);
if (j != null) best = Math.max(best, i - j);
}
return best;
}
}
func findMaxLength(nums []int) int {
first := map[int]int{0: -1} // balance -> first index it was seen
pre, best := 0, 0
for i, x := range nums {
if x == 1 {
pre++
} else {
pre--
}
if j, ok := first[pre]; ok {
best = max(best, i-j)
} else {
first[pre] = i
}
}
return best
}