397. Contiguous Array
You are given a binary array nums containing only the values 0 and 1.
Return the length of the longest contiguous subarray that holds exactly as many 0s as 1s. If no such subarray exists (for example, when every element is the same), return 0.
Only the count matters, not the arrangement — [0, 1] and [1, 0] are both balanced.
Example 1:
Input: nums = [1, 0, 1, 1, 0, 0, 1]
Output: 6
Explanation: The first six elements [1, 0, 1, 1, 0, 0] contain three 1s and three 0s. No balanced subarray of length 7 exists because the whole array has four 1s and three 0s.
Example 2:
Input: nums = [0, 1, 0]
Output: 2
Explanation: Both [0, 1] and [1, 0] are balanced with one of each; a length-3 subarray can never balance since 3 is odd.
Constraints:
- 1 ≤ nums.length ≤ 10⁵
- nums[i] is 0 or 1
Hints:
Recast the array: treat every 1 as +1 and every 0 as -1. A subarray is balanced exactly when its recast sum is 0.
Track the running balance (count of 1s minus count of 0s) while scanning. If the balance takes the same value at two positions, the elements between them sum to zero — hash each balance value to the first index where it occurred, seeded with {0: -1}, and measure i - first[balance].
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: nums = [1, 0, 1, 1, 0, 0, 1]
Expected output: 6