Contiguous Array - Problem
Find the Longest Balanced Subarray

Given a binary array containing only 0s and 1s, your task is to find the maximum length of a contiguous subarray that has an equal number of 0s and 1s.

Think of this as finding the longest "balanced" segment in your binary array - where every 0 is perfectly matched with a 1.

Example: In [0,1,0,0,1,1,0], the subarray [0,1,0,0,1,1] has 3 zeros and 3 ones, giving us a maximum length of 6.

Goal: Return the length of the longest such balanced subarray, or 0 if no balanced subarray exists.

Input & Output

example_1.py โ€” Balanced subarray found
$ Input: [0,1]
โ€บ Output: 2
๐Ÿ’ก Note: The entire array has 1 zero and 1 one, so the maximum length is 2.
example_2.py โ€” Longer balanced subarray
$ Input: [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, giving maximum length 6.
example_3.py โ€” No balanced subarray
$ Input: [0,0,0]
โ€บ Output: 0
๐Ÿ’ก Note: There are only zeros, no ones, so no balanced subarray exists. Return 0.

Visualization

Tap to expand
Contiguous Array: The Hash Map MagicStep 1: Transform0 โ†’ -1, 1 โ†’ +1Equal 0s,1s = sum 0between positionsStep 2: Running SumTrack cumulativesum as we goStore first occurrenceStep 3: Find MatchesSame sum again?Balanced subarray!Calculate lengthStep 4: MaximizeTrack maximumlength foundReturn resultExample: [0,1,0,0,1,1,0]Array:0100110As ยฑ1:-1+1-1-1+1+1-1Sum:0-10-1-2-10-1Balanced! Length = 5-(-1) = 6HashMap Logicโ€ข Sum 0 first seen at index -1 (before start)โ€ข Sum 0 seen again at index 1 โ†’ Subarray [0,1] is balancedโ€ข Sum 0 seen again at index 5 โ†’ Subarray [0,1,0,0,1,1] is balancedโ€ข Length: 5 - (-1) = 6 โœ“ Maximum!๐ŸŽฏ Key Insight: Same running sum = balanced subarray between positions!
Understanding the Visualization
1
Transform the problem
Convert 0โ†’-1, 1โ†’+1. Now equal 0s and 1s mean sum=0 between positions.
2
Track running totals
Maintain running sum and store first occurrence of each sum value.
3
Find matching sums
When same sum appears again, the subarray between has net sum 0 (balanced).
4
Maximize length
Keep track of the longest balanced subarray found.
Key Takeaway
๐ŸŽฏ Key Insight: When the running sum (treating 0 as -1) repeats, the subarray between those positions is perfectly balanced with equal 0s and 1s!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through array with O(1) hashmap operations

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Hashmap stores at most n different running sums

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • nums[i] is either 0 or 1
  • The array contains only binary values
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
42.8K Views
High Frequency
~18 min Avg. Time
1.5K 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