-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubarraySumEqualsK.java
More file actions
36 lines (31 loc) · 1.05 KB
/
SubarraySumEqualsK.java
File metadata and controls
36 lines (31 loc) · 1.05 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
package solutions;
import java.util.HashMap;
import java.util.Map;
// [Problem] https://leetcode.com/problems/subarray-sum-equals-k
class SubarraySumEqualsK {
// Hashmap storing prefix sum
// O(n) time, O(n) space
public int subarraySum(int[] nums, int k) {
int count = 0, sum = 0;
Map<Integer, Integer> sumCounts = new HashMap<>();
sumCounts.put(0, 1);
for (int num : nums) {
sum += num;
if (sumCounts.containsKey(sum - k)) {
count += sumCounts.get(sum - k);
}
int sumCount = sumCounts.getOrDefault(sum, 0);
sumCounts.put(sum, sumCount + 1);
}
return count;
}
// Test
public static void main(String[] args) {
SubarraySumEqualsK solution = new SubarraySumEqualsK();
int[] nums = {3, 4, 7, 2, -3, 1, 4, 2};
int k = 7;
int expectedOutput = 4;
int actualOutput = solution.subarraySum(nums, k);
System.out.println("Test passed? " + (expectedOutput == actualOutput));
}
}