974. 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

 

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:

https://leetcode.com/problems/subarray-sums-divisible-by-k/discuss/217980/Java-O(N)-with-HashMap-and-prefix-Sum

 

posted @ 2019-04-12 22:00  Veritas_des_Liberty  阅读(439)  评论(0编辑  收藏  举报