Last Updated: 1 Dec, 2021

Subarrays With Zero Sum

Easy
Asked in companies
AmazonOYOMicrosoft

Problem statement

You are given ‘N’ integers in the form of an array ‘ARR’. Count the number of subarrays having their sum as 0.

For example :
Let ‘ARR’ be: [1, 4, -5]
The subarray [1, 4, -5] has a sum equal to 0. So the count is 1.
Input Format :
The first line of input contains an integer ‘T’, denoting the number of test cases.

The first line of each test case contains an integer, ‘N’, representing the size of the array.

The second line of each test case contains ‘N’ space-separated integers, representing the array ‘ARR’ elements.
Output Format :
For each test case, print the sorted array.

Print output of each test case in a separate line.
Note :
You do not need to print anything. It has already been taken care of. Just implement the given function. 
Constraints :
1 <= T <= 10
1 <= N <= 10^5
-10^5 <= ARR[i] <= 10^5

Time Limit: 1 sec

Approaches

01 Approach

The basic idea is to find all the subarrays of the array and check whether the sum of that subarray is 0. If the sum is zero, we increase our count.

 

Here is the algorithm :
 

  1. Create a variable (say, ‘COUNT’) to store the number of subarrays with 0 sum and initialize it with 0.
  2. Run a loop from 1 to ‘N’ (say, iterator ‘i’).
    • Create a variable (say, ‘localSum’) to store the subarray sum.
    • Run a loop from ‘i’ to ‘N’ (say, iterator ‘j’).
      • Add the current element to ‘localSum’.
      • Check if ‘localSum’ is equal to 0.
        • Increment ‘COUNT’ by 1.
  3. Return ‘COUNT’.

02 Approach

The basic idea is to store the sum of the array while traversing the array. We store the sum of the elements traveled. Whenever we find a sum already present in a hashmap, we increase our count by the value stored in the hashmap. 
 

For example: 

If we have a subarray starting from index 0 and ending at index 2 has a sum of 10.

If there is another subarray starting from index 0 and ending at index 5 has a sum of 10.

Then the sum of elements from index 3 to index 5 should be 0.

In this way, we can find the number of subarrays having sum 0 by using the hashmap. For each sum found, we add it to our hashmap. 

 

Here is the algorithm :

 

  1. Create a variable (say, ‘COUNT’) to store the count of subarrays with 0 sum.
  2. Create a hashmap (say, ‘MAP’) to store the sum count and initialize ‘MAP[0]’ to 1.
  3. Create a variable (say, ‘localSum’) to store the sum of elements traveled so far and initialize it with 0.
  4. Run a loop from 1 to ‘N’ (say, iterator ‘i’).
    • Add ‘ARR[i]’ to ‘localSum’.
    • Check if ‘localSum’ is present in ‘MAP’.
      • Add ‘MAP[localSum]’ to ‘COUNT’.
    • Add ‘localSum’ to ‘MAP’.
  5. Return ‘COUNT’.