Prefix Sum and Sliding Window 05

Given an array of 0's and 1's. Find the length of the largest subarray with equal number of 0's and 1's.

Problem link :- click here


Code



import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

//	LONGEST SUBARRAY WITH EQUAL NUMBER OF 0's AND 1;s

public class Prefix_sum__Sliding_window_05
{
	
	static int longestSubarrayWith0sAnd1s(int[] arr)
	{
		/*
		 	If we convert this problem to problem number 2, then it will be easy.
		 	In problem 2 we find the sub-array with sum == 0.
		 	In this problem, the given array contains only 0's and 1's.
		 	If we replace 0's with -1's, then this is exactly the same problem. 
		 */
		
		//	Replacing 0 with -1
		for(int i=0; i<arr.length; i++)
			arr[i] = (arr[i] == 0)? -1:1;
		
		Map<Integer, Integer> hp = new HashMap<>();
		int starting_index = -1;
		int ending_index = -1;
		int maxLen = 0;
		
		int sum = 0;
		for(int i=0; i<arr.length; i++)
		{
			sum += arr[i];
			
			if(sum==0)
			{
				maxLen = i + 1;
				ending_index = i;
			}
			
			if( hp.containsKey(sum) )
			{
				if(maxLen < ( i - hp.get(sum) ))
				{
					maxLen = i - hp.get(sum);
					ending_index = i;
				}
			}
			else
				hp.put(sum, i);
		}
		
		starting_index = ending_index - (maxLen - 1);
		System.out.println("from " + starting_index + " to " + ending_index);
		
		return maxLen;
	}

	public static void main(String[] args)
	{
		Scanner s = new Scanner(System.in);
		
		//	Taking size of array and array as input from the user
		System.out.print("Enter the size of the array : ");
		int n = s.nextInt();
		
		int[] arr = new int[n];
		System.out.println("Enter the array elements : ");
		for(int i=0; i<n; i++)
			arr[i] = s.nextInt();
		
		int len = longestSubarrayWith0sAnd1s(arr);
		System.out.println("\nLen = " + len);
	}

}



Comments