-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSubArraySumEqK.java
More file actions
32 lines (27 loc) · 894 Bytes
/
SubArraySumEqK.java
File metadata and controls
32 lines (27 loc) · 894 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
import java.util.HashMap;
import java.util.Map;
public class SubArraySumEqK {
public static void main(String[] args) {
int[] nums = {1,1,1};
System.out.println(subarraySum(nums,2));
}
public static int subarraySum(int[] nums, int k) {
int sum = 0, result = 0;
Map<Integer, Integer> preSum = new HashMap<>();
preSum.put(0, 1);
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
if (preSum.containsKey(sum - k)) {
result += preSum.get(sum - k);
}
preSum.put(sum, preSum.getOrDefault(sum, 0) + 1);
}
return result;
}
}
/*
Time complexity is O(n)
Space complexity is O(n)
Prefix sum is the sum of current number + it's previous sums.
We use that to be able to traverse the array in one pass while finding subarrays that sum are equal to k.
*/