Contiguous Array - Problem
Find the Longest Balanced Subarray
Given a binary array containing only
Think of this as finding the longest "balanced" segment in your binary array - where every 0 is perfectly matched with a 1.
Example: In
Goal: Return the length of the longest such balanced subarray, or 0 if no balanced subarray exists.
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
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
โ Linear Growth
Space Complexity
O(n)
Hashmap stores at most n different running sums
โก Linearithmic Space
Constraints
- 1 โค nums.length โค 105
- nums[i] is either 0 or 1
- The array contains only binary values
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code