1. Introduction
Finding subarrays in an array with specific characteristics is a common problem in data structure and algorithms. In this problem, given an array of 0’s and 1’s, we are tasked to find the maximum length subarray which has an equal number of 0’s and 1’s.
2. Program Steps
1. Replace all 0’s in the array with -1. This will help us use the prefix sum approach to determine the sum at each index.
2. Initialize a Map
3. Iterate over the array, calculate the prefix sum for every index, and check for two conditions:
a. If the sum becomes zero, it means from the start of the array to the current index we have an equal number of 1’s and -1’s.
b. If the sum is already present in the map, the subarray between the previous index (where this sum was found) and the current index has an equal number of 1’s and -1’s.
3. Code Program
public class MaxLengthSubarray {
public static int findMaxLength(int[] arr) {
// Step 1: Replace 0's with -1
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 0) {
arr[i] = -1;
}
}
java.util.Map<Integer, Integer> sumToIndex = new java.util.HashMap<>();
int sum = 0, maxLength = 0;
// Step 3: Calculate prefix sum and check conditions
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
if (sum == 0) {
maxLength = i + 1;
} else if (sumToIndex.containsKey(sum)) {
maxLength = Math.max(maxLength, i - sumToIndex.get(sum));
} else {
sumToIndex.put(sum, i);
}
}
return maxLength;
}
public static void main(String[] args) {
int[] arr = {0, 1, 0, 1, 0, 1, 0};
System.out.println("Maximum length of subarray with equal 0's and 1's is: " + findMaxLength(arr));
}
}
Output:
Maximum length of subarray with equal 0's and 1's is: 6
4. Step By Step Explanation
1. By replacing 0's with -1, we are effectively converting the problem into finding the maximum length subarray with a sum of 0.
2. With the help of a map, we are storing the prefix sum for each index, which represents the difference between the count of 1's and -1's up to the current index.
3. If we encounter a sum that is already in the map, it means there's a subarray between the previous index and current index with equal number of 1's and -1's (or sum = 0).
4. The result gives the length of the longest such subarray with an equal number of 1's and 0's (or -1's after our transformation).