Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.
Example 1:
Input: [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.
Example 2:
Input: [0,1,0]
Output: 2
Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.
Note: The length of the given binary array will not exceed 50,000.
The first natural idea is to run a sliding window and keep adding/discarding elements from both ends. But in this problem, we do not know when exactly to discard one element because this element can be potentially used later to get a longer subarray of equal counts of 0 and 1.
A better approach is to use a hash map to store previous checked prefix subarray results. Keep a running sum, add 1 to it if the current element is 1, add -1 to it if 0. This way, we are looking for the longest subarray that has sum 0. A subarray of sum 0 is equivalent to two different prefix subarrays having the same sum. Remember to initialize empty subarray's index to -1.
class Solution { public int findMaxLength(int[] nums) { int ans = 0; Map<Integer, Integer> map = new HashMap<>(); int sum = 0; map.put(0, -1); for(int i = 0; i < nums.length; i++) { sum += (nums[i] == 0 ? -1 : 1); if(map.containsKey(sum)) { ans = Math.max(ans, i - map.get(sum)); } else { map.put(sum, i); } } return ans; } }
Related Problems
[LeetCode 560] Subarray Sum Equals K
[LeetCode 1371] Find the Longest Substring Containing Vowels in Even Counts