Subarray with given sum | Subarray with sum 0 | Number of subarray with equal number of 0 and 1

Given an array A of size N. You need to print the total count of sub-arrays having their sum equal to x.

Watch my video to understand more about the problem statement and how to solve it :
https://youtu.be/XVAMnJluQIk

public static int findSubArrayWithSumZero(int arr[], int x) {

	HashMap<Integer, Integer> map = new HashMap<>();
	int sum =0;
	int count=0;
	map.put(0, 1);

	for(int i=0;i<arr.length;i++) {

		sum=sum+arr[i];

		if(map.containsKey(sum-x))
			count+=map.get(sum-x);

		if(!map.containsKey(sum))
			map.put(sum,1);

		else
			map.put(sum, map.get(sum)+1);
	}

	return count;

}

Leave a Reply

Your email address will not be published.