Contiguous Array

Longest contiguous subarray with equal numbers of 0s and 1s — prefix sum with `+1/-1` encoding.

Medium
Time O(N) Space O(N)
LeetCode
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#

Contiguous Array
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;
}
};

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#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.