Given an array, find and return the length of longest subarray containing equal number of 0s and 1s. code example

Example 1: Find maximum length sub-array having equal number of 0’s and 1’s

def findMaxLenSublist(A):
 
    # create an empty dictionary to store the ending index of the first
    # sublist having some sum
    dict = {}
 
    # insert `(0, -1)` pair into the set to handle the case when a
    # sublist with zero-sum starts from index 0
    dict[0] = -1
 
    # `length` stores the maximum length of sublist with zero-sum
    length = 0
 
    # stores ending index of the maximum length sublist having zero-sum
    ending_index = -1
 
    sum = 0
 
    # Traverse through the given list
    for i in range(len(A)):
 
        # sum of elements so far (replace 0 with -1)
        sum += -1 if (A[i] == 0) else 1
 
        # if the sum is seen before
        if sum in dict:
 
            # update length and ending index of maximum length
            # sublist having zero-sum
            if length < i - dict.get(sum):
                length = i - dict.get(sum)
                ending_index = i
 
        # if the sum is seen for the first time, insert the sum with its
        # index into the dictionary
        else:
            dict[sum] = i
 
    # print the sublist if present
    if ending_index != -1:
        print((ending_index - length + 1, ending_index))
    else:
        print("No sublist exists")

Example 2: largest subarray of 0's and 1's

public class Solution {

    public int findMaxLength(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, -1);
        int maxlen = 0, count = 0;
        for (int i = 0; i < nums.length; i++) {
            count = count + (nums[i] == 1 ? 1 : -1);
            if (map.containsKey(count)) {
                maxlen = Math.max(maxlen, i - map.get(count));
            } else {
                map.put(count, i);
            }
        }
        return maxlen;
    }
}

Tags:

Java Example