Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding
Ninjas X Naukri.com

Last Updated: 1 Dec, 2021

Easy

```
Let ‘ARR’ be: [1, 4, -5]
The subarray [1, 4, -5] has a sum equal to 0. So the count is 1.
```

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

```
For each test case, print the sorted array.
Print output of each test case in a separate line.
```

```
You do not need to print anything. It has already been taken care of. Just implement the given function.
```

```
1 <= T <= 10
1 <= N <= 10^5
-10^5 <= ARR[i] <= 10^5
Time Limit: 1 sec
```

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 :**

- Create a variable (say, ‘COUNT’) to store the number of subarrays with 0 sum and initialize it with 0.
- 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.

- Return ‘COUNT’.

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.

- Create a variable (say, ‘COUNT’) to store the count of subarrays with 0 sum.
- Create a hashmap (say, ‘MAP’) to store the sum count and initialize ‘MAP[0]’ to 1.
- Create a variable (say, ‘localSum’) to store the sum of elements traveled so far and initialize it with 0.
- 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’.

- Return ‘COUNT’.

Similar problems

Merge Two Sorted Arrays Without Extra Space

Moderate

Posted: 19 Nov, 2022

Merge Two Sorted Arrays Without Extra Space

Moderate

Posted: 19 Nov, 2022

Ninja And The Strictly Increasing Array

Moderate

Posted: 27 Nov, 2022

Maximum GCD

Hard

Posted: 8 Dec, 2022

Negative To The End

Easy

Posted: 16 Dec, 2022

Find Duplicate in Array

Easy

Posted: 5 Jun, 2023