Subarray Sums Divisible by K

Given an array A of integers, return the number of (contiguous, non-empty) subarrays that have a sum divisible by K.

 

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. 1 <= A.length <= 30000
  2. -10000 <= A[i] <= 10000
  3. 2 <= K <= 10000

Solution:

class Solution {
    public int subarraysDivByK(int[] A, int K) {
        int n = A.length;
        Map<Integer, Integer> map = new HashMap();
        map.put(0, 1);
        int res = 0;
        int prefixSum = 0;
        for (int i = 0; i < n; i ++) {
            int val = A[i];
            prefixSum += val;
            int mod = Math.floorMod(prefixSum, K);
            // System.out.println(mod + ", " + map);
            if (map.containsKey(mod)) {
                res += map.get(mod);
            }
            map.put(mod, map.getOrDefault(mod, 0) + 1);
        }
        return res;
    }
}