Skip to content

Commit 32bb838

Browse files
Create 0974-subarray-sums-divisible-by-k.java
1 parent d41772a commit 32bb838

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution {
2+
public int subarraysDivByK(int[] nums, int k) {
3+
int prefix_sum = 0;
4+
int res = 0;
5+
Map<Integer, Integer> map = new HashMap<>(); // remainder -> count
6+
map.put(0, 1);
7+
8+
for(int n: nums){
9+
prefix_sum += n;
10+
int remainder = ((prefix_sum % k) + k) % k; // twice modulo to avoid negative remainders
11+
12+
res += map.getOrDefault(remainder, 0);
13+
map.put(remainder, map.getOrDefault(remainder, 0) + 1);
14+
}
15+
return res;
16+
}
17+
}

0 commit comments

Comments
 (0)