forked from Anuj-Kumar-Sharma/DS-Algo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubarrayWithZeroSum.java
More file actions
47 lines (37 loc) · 899 Bytes
/
SubarrayWithZeroSum.java
File metadata and controls
47 lines (37 loc) · 899 Bytes
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
47
package interviewQuestions;
/*
* Given an array, find if there exists a subarray with sum equals to zero.
* n < 10^5
*/
import java.util.*;
public class SubarrayWithZeroSum {
public static void main(String[] args) {
int[] a = { 2, 1, 3, -4, -2 };
int k = -3;
boolean found = false;
// for(int i = 0; i<a.length; i++) {
// int sum = 0;
// for(int j = i; j<a.length; j++) {
// sum += a[j];
// if(sum == 0) {
// found = true;
// break;
// }
// }
// if(found) break;
// }
Set<Integer> set = new HashSet<>();
int sum = 0;
for (int element : a) {
set.add(sum);
sum += element;
//Zero sum will only exist if the cumulative sum of the elements excluding the current element
//and after including the current element are equal
if (set.contains(sum - k)) {
found = true;
break;
}
}
System.out.println("found " + found);
}
}