DSA problem
Contiguous Array
Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1.
The classic transformation is to treat every 0 as -1. After this remapping, a subarray with an equal count of zeros and ones becomes a subarray whose sum is exactly 0. Finding the longest zero-sum subarray reduces to a prefix-sum problem: if the running sum repeats at two indices, the elements between them sum to zero. By recording the first index at which each running-sum value appears, we can compute the longest balanced subarray in a single linear pass.
Examples
Example 1
Input:
nums = [0,1]Output:
2Explanation: [0,1] is the longest contiguous subarray with an equal number of 0 and 1.
Example 2
Input:
nums = [0,1,0]Output:
2Explanation: [0,1] or [1,0] is the longest contiguous subarray with an equal number of 0 and 1.
Example 3
Input:
nums = [0,1,1,1,1,1,0,0,0]Output:
6Explanation: The subarray [1,1,1,0,0,0] from index 3 to 8 has three ones and three zeros, giving length 6.
Constraints
- 1 <= nums.length <= 10^5
- nums[i] is either 0 or 1.
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.