Coding Interview PatternsContiguous Array
MediumHash Maps
Contiguous Array
Explanation & Solution
Description
Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1.
Input:nums = [0, 1]
0
0
1
1
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with an equal number of 0 and 1.
Constraints
1 <= nums.length <= 10⁵nums[i]is either0or1
Approach
Hash Maps pattern
1. Transform the Problem
- Treat each
0as-1and each1as+1 - Now the problem becomes: find the longest subarray with a sum of
0 - This is equivalent to finding equal numbers of 0s and 1s
2. Use a Prefix Sum with a Hash Map
- Maintain a running
count(prefix sum) as we scan left to right - Create a hash map
prefixMapthat maps each prefix sum value to the earliest index where it occurred - Initialize with
prefixMap.set(0, -1)to handle the case where the subarray starts from index 0
3. Scan Through the Array
- For each index
i, updatecount: add+1for1, add-1for0 - If
counthas been seen before at indexj, then the subarray fromj+1toihas a sum of 0, meaning equal 0s and 1s - Update
maxLen = Math.max(maxLen, i - j) - If
counthas not been seen before, store the current index as its first occurrence
4. Return the Maximum Length
- After processing all elements,
maxLenholds the length of the longest contiguous subarray with equal 0s and 1s
Key Insight
- If the prefix sum at index
iequals the prefix sum at indexj, then the elements betweenj+1andimust sum to 0 — meaning equal counts of 0 and 1 - We only store the first occurrence of each prefix sum to maximize the subarray length
Time
O(n)single pass through the arraySpace
O(n)the hash map stores at most n+1 distinct prefix sumsVisualization
Input:
[0, 1]
—
No animation available
Left (L)Right (R)ConvergedDone
0 steps