Skip to content

Commit ab6d2bf

Browse files
authored
Create subarray-sums-divisible-by-k.cpp
1 parent fa6473d commit ab6d2bf

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

C++/subarray-sums-divisible-by-k.cpp

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// Time: O(n)
2+
// Space: O(k)
3+
4+
class Solution {
5+
public:
6+
int subarraysDivByK(vector<int>& A, int K) {
7+
unordered_map<int, int> count;
8+
count[0] = 1;
9+
int prefix = 0, result = 0;
10+
for (const auto& a : A) {
11+
prefix = (prefix + (a % K + K)) % K;
12+
result += count[prefix]++;
13+
}
14+
return result;
15+
}
16+
};

0 commit comments

Comments
 (0)