Contiguous Array
Problem Link
525. Contiguous Array – LeetCode
Problem Statement
Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1.
Examples
Example 1:
Input: nums = [0, 1]
Output: 2
Explanation: [0, 1] has 1 zero and 1 one → length 2.
Example 2:
Input: nums = [0, 1, 0]
Output: 2
Explanation: [0, 1] or [1, 0] → both have equal 0s and 1s.
Example 3:
Input: nums = [0,1,1,1,1,1,0,0,0]
Output: 6
Explanation: [1,1,1,0,0,0] has equal 0s and 1s (3 of each).
Constraints
-
1 <= nums.length <= 10⁵ -
nums[i]is either0or1
Intuition
To solve the problem in linear time, we transform the array:
-
Treat
0as-1, and1as+1 -
The task becomes: Find the longest subarray with sum = 0
Why?
- Because an equal number of
+1and-1implies equal number of1and0
We use a HashMap to track the first occurrence of each cumulative sum (prefix sum). If we see the same prefix sum again, the subarray between the two indices has a net sum of 0.
Approach
-
Initialize
sum = 0,maxLen = 0, and an emptyMap<sum, index> -
Iterate through the array:
-
Add
+1for every1,-1for every0tosum -
If
sum == 0, the subarray from start to current index is valid → updatemaxLen -
If
sumis already in the map:- A previous subarray led to this sum → current subarray from
map.get(sum) + 1toihas net sum = 0 → updatemaxLen
- A previous subarray led to this sum → current subarray from
-
Else, store the current index for this sum in map
-
-
Return
maxLen
Java Code
class Solution {
public int findMaxLength(int[] nums) {
int sum = 0;
int maxLen = 0;
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
// Transform 0 to -1
sum += nums[i] == 0 ? -1 : 1;
if (sum == 0) {
maxLen = i + 1;
} else if (map.containsKey(sum)) {
maxLen = Math.max(maxLen, i - map.get(sum));
} else {
map.put(sum, i);
}
}
return maxLen;
}
}
Time and Space Complexity
| Operation | Time Complexity | Space Complexity |
|---|---|---|
| Single Pass | O(n) | O(n) |
| HashMap Storage | O(n) | O(n) |
Dry Run
Input:
nums = [0, 1, 0]
Transformed:
[-1, +1, -1]
| i | nums[i] | sum | map | maxLen |
|---|---|---|---|---|
| 0 | 0 | -1 | 0 | |
| 1 | 1 | 0 | 2 | |
| 2 | 0 | -1 | 2 → [1,0] |
Key Observations
-
Prefix sum is used to efficiently track the balance between 0s and 1s
-
The map stores first occurrences only to maximize subarray length
-
Resetting sum to zero means equal 0s and 1s from index
0toi
Conclusion
This is a classic application of prefix sum with hashmap to convert a two-value balancing problem into a sum-equals-zero subarray problem.
You should consider this approach whenever you're asked to:
-
Count equal numbers of two values
-
Track balance or neutrality in an array