Subarrays With Zero Sum

Easy
0/40
profile
Contributed by
48 upvotes
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.
Detailed explanation ( Input/output format, Notes, Images )
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
Sample Input 1 :
2
3
1 4 -5
4
-1 1 0 1
Sample Output 1 :
1
3
Explanation For Sample Output 1 :
For test case 1: 
The subarray [1, 4, -5] has a sum equal to 0. 
So the count is 1.

For test case 2: 
The subarray [-1, 1], [-1, 1, 0] and  [0] has a sum equal to 0. 
So the count is 3.
Sample Input 2 :
2
4
-1 0 1 -1
3
-2 0 2
Sample Output 2 :
4
2
Hint

Try to check all the subarrays.

Approaches (2)
Brute Force

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

O(N^2), where ‘N’ is the size of the array.

 

We run a loop to traverse all the elements of the array, which takes O(N) time, and for each element, we again run a loop to make subarrays starting from the current element, which takes O(N) time. Therefore, the overall time complexity will be O(N^2).

Space Complexity

O(1)

 

We don’t use any extra space. Therefore, the overall space complexity will be O(1).

Code Solution
(100% EXP penalty)
Subarrays With Zero Sum
Full screen
Console