Count pairs in array whose sum is divisible by K

Given an array A[] and positive integer K, the task is to count total number of pairs in the array whose sum is divisible by K. Note : This question is generalised version of this

Examples:

Input : A[] = {2, 2, 1, 7, 5, 3}, K = 4
Output : 5
Explanation : 
There are five pairs possible whose sum
is divisible by '4' i.e., (2, 2), 
(1, 7), (7, 5), (1, 3) and (5, 3)

Input : A[] = {5, 9, 36, 74, 52, 31, 42}, K = 3
Output : 7
class Solution {
    public int[] pairSumDivByK(int[] A, int K) {
        // Map of (Remainder after % K) -> Frequency
        Map<Integer, Integer> map = new HashMap<>();
        int count = 0;
        for (int x : A) {
            int mod = x % K;
            int pairValue = K - mod;
            if (map.containsKey(pairValue))
                count += map.get(pairValue);
            map.put(mod, map.getOrDefault(mod, 0) + 1);
        }
        return count;
    }
}

Last updated