-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathZero_Sum_Subarrays.java
45 lines (37 loc) · 931 Bytes
/
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
// { Driver Code Starts
//Initial Template for Java
/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
sc.nextLine();
while (t-- > 0) {
int n;
n = sc.nextInt();
long arr[] = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextLong();
}
Solution ob = new Solution();
System.out.println(ob.findSubarray(arr, n));
}
}
}
class Solution {
public static long findSubarray(long[] arr, int n) {
HashMap<Long, Integer> map = new HashMap<>();
long sum = 0, count = 0;
for (long a : arr) {
sum += a;
if (sum == 0)
count++;
if (map.containsKey(sum))
count += map.get(sum);
map.put(sum, map.getOrDefault(sum, 0) + 1);
}
return count;
}
}