-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubArrayZero.java
More file actions
49 lines (38 loc) · 1.17 KB
/
SubArrayZero.java
File metadata and controls
49 lines (38 loc) · 1.17 KB
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
48
49
package datastructure.hashtable;
import java.util.HashMap;
/**
* The type Sub array zero.
*/
public class SubArrayZero {
/**
* Find sub zero boolean.
*
* @param arr the arr
* @return the boolean
*/
public static boolean findSubZero(int[] arr) {
//Use HashMap to store Sum as key and index i as value till sum has been calculated.
//Traverse the array and return true if either
//arr[i] == 0 or sum == 0 or HashMap already contains the sum
//If you completely traverse the array and havent found any of the above three
//conditions then simply return false.
HashMap<Integer, Integer> hMap = new HashMap<>();
int sum = 0;
// Traverse through the given array
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
if (arr[i] == 0 || sum == 0 || hMap.get(sum) != null) return true;
hMap.put(sum, i);
}
return false;
}
/**
* Main.
*
* @param args the args
*/
public static void main(String args[]) {
int[] arr = {6, 4, 19, -2, 2, 12, 9};
System.out.println(findSubZero(arr));
}
}