Contiguous Array - Problem
Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0s and 1s.
A contiguous subarray is a sequence of adjacent elements in the array.
Example: For array [0,1,0,0,1,1,0], the subarray [0,1,0,0,1,1] has 3 zeros and 3 ones, so the maximum length is 6.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [0,1]
›
Output:
2
💡 Note:
The entire array has 1 zero and 1 one, so the maximum length is 2
Example 2 — Longer Array
$
Input:
nums = [0,1,0,0,1,1,0]
›
Output:
6
💡 Note:
The subarray [0,1,0,0,1,1] from index 0 to 5 has 3 zeros and 3 ones, length = 6
Example 3 — All Same
$
Input:
nums = [0,0,0,0]
›
Output:
0
💡 Note:
No subarray has equal number of 0s and 1s, so return 0
Constraints
- 1 ≤ nums.length ≤ 105
- nums[i] is either 0 or 1
Visualization
Tap to expand
Understanding the Visualization
1
Input
Binary array with 0s and 1s
2
Process
Find longest subarray with equal count
3
Output
Maximum length found
Key Takeaway
🎯 Key Insight: Transform 0s to -1s and find longest zero-sum subarray using prefix sums
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code