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
Contiguous Array ProblemFind maximum length subarray with equal 0s and 1s0100110Input: [0, 1, 0, 0, 1, 1, 0]Longest valid subarray3 zeros + 3 ones = 6 elementsOutput: 6
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
Asked in
Facebook 45 Google 35 Amazon 30
180.0K Views
Medium Frequency
~25 min Avg. Time
3.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen