AlgoInsight

DSA problem

Contiguous Array

MediumPrefix SumPattern: Prefix Sum + Hash Maptop150FacebookAmazonGoogleMicrosoft

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: 2
Explanation: [0,1] is the longest contiguous subarray with an equal number of 0 and 1.
Example 2
Input: nums = [0,1,0]
Output: 2
Explanation: [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: 6
Explanation: The subarray [1,1,1,0,0,0] from index 3 to 8 has three ones and three zeros, giving length 6.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

prefix-sumhash-maparray

Browse all DSA problems