Contiguous Array
Longest contiguous subarray with equal numbers of 0s and 1s — prefix sum with `+1/-1` encoding.
3 min read
hash-map prefix-sum
Problem#
Given a binary array nums, return the length of the longest contiguous subarray with an equal number of 0 and 1.
Examples#
[0,1]→2.[0,1,0]→2.[0,0,1,0,0,0,1,1]→6.
Constraints#
1 <= nums.length <= 10^5.
Hints#
Hint
Treat 0 as -1; equal counts means prefix sum stays the same at two points.
Approach#
Walk the array, treating 0 as -1 and 1 as +1, accumulating sum. Store firstSeen[sum] = i. When sum reappears at index j, the subarray (i, j] has equal counts of 0s and 1s. Initialize firstSeen[0] = -1 so a prefix that itself is balanced counts.
Solution#
class Solution {public: int findMaxLength(vector<int>& nums) { unordered_map<int,int> firstSeen; firstSeen[0] = -1; int sum = 0, ans = 0; for (int i = 0; i < (int)nums.size(); ++i) { sum += nums[i] == 1 ? 1 : -1; auto it = firstSeen.find(sum); if (it != firstSeen.end()) ans = max(ans, i - it->second); else firstSeen[sum] = i; } return ans; }};func findMaxLength(nums []int) int { firstSeen := map[int]int{0: -1} sum, ans := 0, 0 for i, v := range nums { if v == 1 { sum++ } else { sum-- } if j, ok := firstSeen[sum]; ok { if i-j > ans { ans = i - j } } else { firstSeen[sum] = i } } return ans}from typing import List
class Solution: def findMaxLength(self, nums: List[int]) -> int: first_seen = {0: -1} total, ans = 0, 0 for i, v in enumerate(nums): total += 1 if v == 1 else -1 if total in first_seen: ans = max(ans, i - first_seen[total]) else: first_seen[total] = i return ansfunction findMaxLength(nums) { const firstSeen = new Map(); firstSeen.set(0, -1); let sum = 0, ans = 0; for (let i = 0; i < nums.length; i++) { sum += nums[i] === 1 ? 1 : -1; if (firstSeen.has(sum)) { ans = Math.max(ans, i - firstSeen.get(sum)); } else { firstSeen.set(sum, i); } } return ans;}class Solution { public int findMaxLength(int[] nums) { Map<Integer, Integer> firstSeen = new HashMap<>(); firstSeen.put(0, -1); int sum = 0, ans = 0; for (int i = 0; i < nums.length; i++) { sum += nums[i] == 1 ? 1 : -1; if (firstSeen.containsKey(sum)) { ans = Math.max(ans, i - firstSeen.get(sum)); } else { firstSeen.put(sum, i); } } return ans; }}function findMaxLength(nums: number[]): number { const firstSeen = new Map<number, number>(); firstSeen.set(0, -1); let sum = 0, ans = 0; for (let i = 0; i < nums.length; i++) { sum += nums[i] === 1 ? 1 : -1; const prev = firstSeen.get(sum); if (prev !== undefined) { ans = Math.max(ans, i - prev); } else { firstSeen.set(sum, i); } } return ans;}Editorial#
The +1/-1 encoding turns “equal counts” into “equal prefix sums” — a difference of zero. We keep the first occurrence of each sum to maximize window length on later revisits. The firstSeen[0] = -1 sentinel allows the whole prefix from index 0 to count.
Complexity#
- Time: O(N).
- Space: O(N).
Concept revision#
Related#