Given an array nums
of integers, return the number of (contiguous, non-empty) subarrays that have a sum divisible by k
.
Example 1:
Input: nums = [4,5,0,-2,-3,1], k = 5 Output: 7 Explanation: There are 7 subarrays with a sum divisible by k = 5: [4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]
Note:
1 <= nums.length <= 30000
-10000 <= nums[i] <= 10000
2 <= k <= 10000
Related Topics:
Array, Hash Table
Similar Questions:
// OJ: https://leetcode.com/problems/subarray-sums-divisible-by-k/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(K)
class Solution {
public:
int subarraysDivByK(vector<int>& A, int k) {
unordered_map<int, int> m{{0,1}};
int sum = 0, ans = 0;
for (int n : A) {
sum += n;
if (sum >= 0) sum %= k;
else sum = (k - (-sum % k)) % k;
ans += m[sum];
m[sum]++;
}
return ans;
}
};