-
Notifications
You must be signed in to change notification settings - Fork 0
/
Zero Sum Subarrays.java
46 lines (32 loc) · 1.01 KB
/
Zero Sum Subarrays.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// Date : 22.12.2022
// problem statement:Zero Sum Subarrays (Mid Level)
// Time complexity : O(N)
// Space complexity : O(N)
class Solution{
//Function to count subarrays with sum equal to 0.
public static long findSubarray(long[] arr ,int n)
{
//long count = 0;
//HashMap<Integer,Integer> map = new HashMap<>();
//return type is long
HashMap <Long , Long> map = new HashMap<>();
long sum=0,count=0;
//itterate the array and find subarray of sum zero
for(long i : arr)
{
sum += i;
// if map contains the key value then add
if(map.containsKey(sum))
{
count += map.get(sum);
}
// while itterating if sum=0 then add 1 to the count value
if(sum ==0)
{
count++;
}
map.put(sum,map.getOrDefault(sum,0l) + 1l);
}
return count;
}
}