VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-pairs-in-array-whose-sum-is-divisible-by-k/

⇱ Count pairs in array whose sum is divisible by K - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count pairs in array whose sum is divisible by K

Last Updated : 16 May, 2026

Given an array arr[] and positive integer k, the task is to count total number of pairs in the array whose sum is divisible by k.

Examples:

Input:  arr[] = {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: arr[] = {5, 9, 36, 74, 52, 31, 42}, k = 3
Output:
Explanation: There are seven pairs whose sum is divisible by 3,
i.e, (9, 36), (9,42), (74, 52), (36, 42), (74, 31), (31, 5) and (5, 52).

[Naive Approach] Using Two Loops - O(n2) Time O(1) Space

The idea is to run two nested loops to consider all possible pairs in the array. For each pair, we check whether If the condition (arr[i] + arr[j]) % k == 0 is satisfied, we increment the count.


Output
5

Time Complexity: O(n2)
Space Complexity: O(1)

[Expected Approach] Using Hashing - O(n + k) Time O(k) Space

The idea is to use a frequency map to count elements based on their remainders when divided by k. Then, pairs are formed by combining remainders i and k - i. Handle remainder 0 separately, and if k is even, also handle k/2.

Let us understand with an example:

Input: arr[] = [2, 2, 1, 7, 5, 3], k = 4

Step 1: Initialize res = 0

Step 2: Build Frequency Map for Remainders
freq{2} = 2 [For 2 & 2]
freq{1} = 2 [For 1 and 5}
freq{3} = {2} [For 7 and 3]

Step 3: Check if there are elements with 0 remainder, we need to add freq{0} * (freq{0} - 1)/2 to the result because every item can form a pair with every other item.
No items with zero remainder in our input example [2, 2, 1, 7, 5, 3] and k = 4

Step 3: Run a loop for i = 1 to k/2 and i is not same as k - i (to avoid counting same number twice)
i = 1: Add freq{1} * freq{4-1} to the result, we get res = res + 2*2 = 0 + 4 = 4
i = 2: Since k - i == i, we break the loop

Step 4: If k is even and freq{k/2} is not zero then we need to count pairs avoiding double counting.
k = 4 and it is even, so we add freq{k/2} * (freq{k/2} - 1)/2 to the result, res = res + (2*(2-1))/2 = 4 + 1 = 5.

All pairs processed. final result = 5


Output
5

Time Complexity: O(n + k) 
Space Complexity: O(k)

Comment
Article Tags: