Algorithm
Problem Name: 974. Subarray Sums Divisible by K
Given an integer array nums
and an integer k
, return the number of non-empty subarrays that have a sum divisible by k
.
A subarray is a contiguous part of an array.
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]
Example 2:
Input: nums = [5], k = 9 Output: 0
Constraints:
1 <= nums.length <= 3 * 104
-104 <= nums[i] <= 104
2 <= k <= 104
Code Examples
#1 Code Example with Java Programming
Code -
Java Programming
class Solution {
public int subarraysDivByK(int[] A, int K) {
int sum = 0;
int count = 0;
Map < Integer, Integer> map = new HashMap<>();
map.put(0, 1);
for (int i = 0; i < A.length; i++) {
sum = (sum + A[i]) % K;
if (sum < 0) {
sum += K;
}
count += map.getOrDefault(sum, 0);
map.put(sum, map.getOrDefault(sum, 0) + 1);
}
return count;
}
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Javascript Programming
Code -
Javascript Programming
const subarraysDivByK = function (nums, k) {
const memo = {0: 1}
let sum = 0, res = 0
for(const e of nums) {
sum += e
const remain = ( sum % k + k) % k
res += memo[remain] ?? 0
memo[remain] = (memo[remain] ?? 0) + 1
}
return res
}
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Python Programming
Code -
Python Programming
class Solution:
def subarraysDivByK(self, A: List[int], K: int) -> int:
res = sm = 0
sums = collections.defaultdict(int)
sums[0] = 1
for a in A:
sm = (sm + a) % K
sums[sm] += 1
res += sums[sm] - 1
return res
Copy The Code &
Try With Live Editor
Input