Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: 1 Dec, 2021

Subarrays With Zero Sum

Easy
Asked in companies
MicrosoftOYOAmazon

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’.