Given an array
Aof integers, return the number of (contiguous, non-empty) subarrays that have a sum divisible byK.
Example 1:
Input: A = [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 <= A.length <= 30000-10000 <= A[i] <= 100002 <= K <= 10000
Approach #1: HashMap. [Java]
class Solution {
public int subarraysDivByK(int[] A, int K) {
HashMap<Integer, Integer> map = new HashMap<>();
int sum = 0, count = 0;
map.put(0, 1);
for (int a : A) {
sum = (sum + a) % K;
if (sum < 0) sum += K;
count += map.getOrDefault(sum, 0);
map.put(sum, map.getOrDefault(sum, 0) + 1);
}
return count;
}
}
Approach #2: Optimize. [Java]
class Solution {
public int subarraysDivByK(int[] A, int K) {
int[] map = new int[K];
int sum = 0, count = 0;
map[0] = 1;
for (int a : A) {
sum = (sum + a) % K;
if (sum < 0) sum += K;
count += map[sum];
map[sum]++;
}
return count;
}
}
Analysis:
About this problems - sum of contigous subarray, prefix sum is a common techinque.
Another thisng is if sum[0, i] % K == sum[0, j] % K, sum[i+1, j] is divisible by K. So for current index j, we need to find out how many index i (i < j) exit that has the same mod for K. Now it easy to come up with HashMap <mod, frequency>
Time complexity: O(N)
Space complexity: O (N)
Reference: