Given an integer array, determine whether it can be divided into pairs such that the sum of elements in each pair is divisible by a given positive integer k.

For example,

Input:
arr[] = { 3, 1, 2, 6, 9, 4 }
k = 5
 
Output: Pairs can be formed
 
Explanation: Array can be divided into pairs {(3, 2), (1, 9), (4, 6)} where the sum of elements in each pair is divisible by 5.
 
 
Input:
arr[] = { 2, 9, 4, 1, 3, 5 }
k = 6
 
Output: Pairs can be formed
 
Explanation: Array can be divided into pairs {(2, 4), (9, 3), (1, 5)} where the sum of elements in each pair is divisible by 6.
 
 
Input:
arr[] = { 3, 1, 2, 6, 9, 4 }
k = 6
 
Output: Pairs cannot be formed
 
Explanation: Array cannot be divided into pairs where the sum of elements in each pair is divisible by 6.

Practice this problem

1. Brute-Force Solution

A naive solution is to iterate over array arr and consider each element arr[i] as the first element of a pair. Then process the remaining elements to find the first non-visited element arr[j] which satisfies the relation (arr[j] + arr[i]) % k == 0. If a pair is found for all elements, return true; otherwise, return false.

The time complexity of this approach is O(n2), where n is the input size and requires O(n) extra space. Following is the C, Java, and Python program that demonstrates it:

C


Download  Run Code

Output:

Pairs can be formed

Java


Download  Run Code

Output:

Pairs can be formed

Python


Download  Run Code

Output:

Pairs can be formed

2. Hashing Solution

We can improve the time complexity to O(n) using hashing. The idea is to traverse the input array and create a map to keep track of remainders of all input elements with k, i.e., create a map whose keys store the remainder and value stores the frequency of the remainder. Then traverse all (remainder, frequency) pairs present on the map.

  • For elements directly divisible by k, the remainder r would be 0, and the frequency should be even.
  • For elements not directly divisible by k and having remainder r, a pair only exists when there is another array element with remainder k-r. Therefore, the frequency of the remainder r must be equal to the frequency of k-r.

If this is not the case for any remainder r in the map, return false; otherwise, return true. Following is the C, C++, Java, and Python program that demonstrates it:

C


Download  Run Code

Output:

Pairs can be formed

C++


Download  Run Code

Output:

Pairs can be formed

Java


Download  Run Code

Output:

Pairs can be formed

Python


Download  Run Code

Output:

Pairs can be formed

The time complexity of the above solution is O(n) and requires O(k) extra space.

 
Note that the above solution won’t work for negative numbers. To handle the negative numbers, increment the negative remainder r by k before updating the count array/map, as shown below: