Given an array of integers and a number k, write a function that returns true if the given array can be divided into pairs such that the sum of every pair is divisible by k.
Examples:
Input: arr[] = {9, 7, 5, 3}, k = 6
Output: True
We can divide the array into (9, 3) and
(7, 5). Sum of both of these pairs
is a multiple of 6.
Input: arr[] = {92, 75, 65, 48, 45, 35}, k = 10
Output: True
We can divide the array into (92, 48), (75, 65).
and (45, 35). The sum of all these pairs is a
multiple of 10.
Input: arr[] = {91, 74, 66, 48}, k = 10
Output: False
A Simple Solution is to iterate through every element arr[i]. Find if there is another not yet visited element that has a remainder like (k – arr[i]%k). If there is no such element, return false. If a pair is found, then mark both elements as visited. The time complexity of this solution is O(n2 and it requires O(n) extra space.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool canPairs( int nums[], int n, int k)
{
if (n % 2 == 1)
return false ;
int count = 0;
vector< int > vis(n, -1);
for ( int i = 0; i < n; i++) {
for ( int j = i + 1; j < n; j++) {
if ((nums[i] + nums[j]) % k == 0
and vis[i] == -1 and vis[j] == -1) {
count++;
vis[i] = 1;
vis[j] = 1;
}
}
}
if (count == n / 2)
return true ;
else
return false ;
}
int main()
{
int arr[] = { 92, 75, 65, 48, 45, 35 };
int k = 10;
int n = sizeof (arr) / sizeof (arr[0]);
canPairs(arr, n, k) ? cout << "True" : cout << "False" ;
return 0;
}
|
Java
import java.util.*;
class GFG {
static boolean canPairs( int nums[], int n, int k)
{
if (n % 2 == 1 )
return false ;
int count = 0 ;
int vis[] = new int [n];
Arrays.fill(vis,- 1 );
for ( int i = 0 ; i < n; i++) {
for ( int j = i + 1 ; j < n; j++) {
if ((nums[i] + nums[j]) % k == 0 && vis[i] == - 1 && vis[j] == - 1 ) {
count++;
vis[i] = 1 ;
vis[j] = 1 ;
}
}
}
if (count == n / 2 )
return true ;
return false ;
}
public static void main (String[] args) {
int arr[] = { 92 , 75 , 65 , 48 , 45 , 35 };
int k = 10 ;
int n = arr.length;
if (canPairs(arr, n, k)){
System.out.println( "True" );
} else {
System.out.println( "False" );
}
}
}
|
Python3
def canPairs(nums, n, k):
if (n % 2 = = 1 ):
return False
count = 0
vis = [ - 1 ] * n
for i in range ( 0 ,n):
for j in range (i + 1 ,n):
if ((nums[i] + nums[j]) % k = = 0 and vis[i] = = - 1 and vis[j] = = - 1 ):
count + = 1
vis[i] = 1
vis[j] = 1
if (count = = n / 2 ):
return True
else :
return False
arr = [ 92 , 75 , 65 , 48 , 45 , 35 ]
k = 10
n = len (arr)
if (canPairs(arr, n, k)):
print ( "True" )
else :
print ( "False" )
|
C#
using System;
using System.Linq;
using System.Collections;
public class GFG
{
public static bool canPairs( int [] nums, int n, int k)
{
if (n % 2 == 1)
{
return false ;
}
var count = 0;
int [] vis = new int [n];
System.Array.Fill(vis,-1);
for ( int i = 0; i < n; i++)
{
for ( int j = i + 1; j < n; j++)
{
if ((nums[i] + nums[j]) % k == 0 && vis[i] == -1 && vis[j] == -1)
{
count++;
vis[i] = 1;
vis[j] = 1;
}
}
}
if (count == ( int )(n / 2))
{
return true ;
}
return false ;
}
public static void Main(String[] args)
{
int [] arr = {92, 75, 65, 48, 45, 35};
var k = 10;
var n = arr.Length;
if (GFG.canPairs(arr, n, k))
{
Console.WriteLine( "True" );
}
else
{
Console.WriteLine( "False" );
}
}
}
|
Javascript
function canPairs(nums, n, k)
{
if (n % 2 === 1)
return false ;
var count = 0;
var vis = new Array(n).fill(-1);
for ( var i = 0; i < n; i++) {
for ( var j = i + 1; j < n; j++) {
if ((nums[i] + nums[j]) % k === 0
&& vis[i] === -1 && vis[j] === -1) {
count++;
vis[i] = 1;
vis[j] = 1;
}
}
}
if (count === n / 2)
return true ;
else
return false ;
}
var arr = [ 92, 75, 65, 48, 45, 35 ];
var k = 10;
var n = arr.length;
canPairs(arr, n, k) ? console.log( "True" ) : console.log( "False" );
|
Time Complexity: O(n^2)
Auxiliary Space: O(n) for creating a visited array
An Efficient Solution is to use Hashing.
1) If length of given array is odd, return false.
An odd length array cannot be divided into pairs.
2) Traverse input array and count occurrences of
all remainders (use (arr[i] % k)+k)%k for handling the case of negative integers as well).
freq[((arr[i] % k) + k) % k]++
3) Traverse input array again.
a) Find the remainder of the current element.
b) If remainder divides k into two halves, then
there must be even occurrences of it as it
forms pair with itself only.
c) If the remainder is 0, then there must be
even occurrences.
d) Else, number of occurrences of current
the remainder must be equal to a number of
occurrences of "k - current remainder".
The idea is to use hashing (unordered_map in C++ and HashMap in Java).
The below image is a dry run of the above approach:

Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool canPairs( int arr[], int n, int k)
{
if (n & 1)
return false ;
unordered_map< int , int > freq;
for ( int i = 0; i < n; i++)
freq[((arr[i] % k) + k) % k]++;
for ( int i = 0; i < n; i++) {
int rem = ((arr[i] % k) + k) % k;
if (2 * rem == k) {
if (freq[rem] % 2 != 0)
return false ;
}
else if (rem == 0) {
if (freq[rem] & 1)
return false ;
}
else if (freq[rem] != freq[k - rem])
return false ;
}
return true ;
}
int main()
{
int arr[] = { 92, 75, 65, 48, 45, 35 };
int k = 10;
int n = sizeof (arr) / sizeof (arr[0]);
canPairs(arr, n, k) ? cout << "True" : cout << "False" ;
return 0;
}
|
Java
import java.util.HashMap;
public class Divisiblepair {
static boolean canPairs( int ar[], int k)
{
if (ar.length % 2 == 1 )
return false ;
HashMap<Integer, Integer> hm = new HashMap<>();
for ( int i = 0 ; i < ar.length; i++) {
int rem = ((ar[i] % k) + k) % k;
if (!hm.containsKey(rem)) {
hm.put(rem, 0 );
}
hm.put(rem, hm.get(rem) + 1 );
}
for ( int i = 0 ; i < ar.length; i++) {
int rem = ((ar[i] % k) + k) % k;
if ( 2 * rem == k) {
if (hm.get(rem) % 2 == 1 )
return false ;
}
else if (rem == 0 ) {
if (hm.get(rem) % 2 == 1 )
return false ;
}
else {
if (hm.get(k - rem) != hm.get(rem))
return false ;
}
}
return true ;
}
public static void main(String[] args)
{
int arr[] = { 92 , 75 , 65 , 48 , 45 , 35 };
int k = 10 ;
boolean ans = canPairs(arr, k);
if (ans)
System.out.println( "True" );
else
System.out.println( "False" );
}
}
|
Python3
from collections import defaultdict
def canPairs(arr, n, k):
if (n & 1 ):
return 0
freq = defaultdict( lambda : 0 )
for i in range ( 0 , n):
freq[((arr[i] % k) + k) % k] + = 1
for i in range ( 0 , n):
rem = ((arr[i] % k) + k) % k
if ( 2 * rem = = k):
if (freq[rem] % 2 ! = 0 ):
return 0
else if (rem = = 0 ):
if (freq[rem] & 1 ):
return 0
else if (freq[rem] ! = freq[k - rem]):
return 0
return 1
arr = [ 92 , 75 , 65 , 48 , 45 , 35 ]
k = 10
n = len (arr)
if (canPairs(arr, n, k)):
print ( "True" )
else :
print ( "False" )
|
C#
using System.Collections.Generic;
using System;
class GFG {
static bool canPairs( int [] ar, int k)
{
if (ar.Length % 2 == 1)
return false ;
Dictionary<Double, int > hm
= new Dictionary<Double, int >();
for ( int i = 0; i < ar.Length; i++) {
int rem = ((ar[i] % k) + k) % k;
if (!hm.ContainsKey(rem)) {
hm[rem] = 0;
}
hm[rem]++;
}
for ( int i = 0; i < ar.Length; i++) {
int rem = ((ar[i] % k) + k) % k;
if (2 * rem == k) {
if (hm[rem] % 2 == 1)
return false ;
}
else if (rem == 0) {
if (hm[rem] % 2 == 1)
return false ;
}
else {
if (hm[k - rem] != hm[rem])
return false ;
}
}
return true ;
}
public static void Main()
{
int [] arr = { 92, 75, 65, 48, 45, 35 };
int k = 10;
bool ans = canPairs(arr, k);
if (ans)
Console.WriteLine( "True" );
else
Console.WriteLine( "False" );
}
}
|
Javascript
<script>
function canPairs(ar, k)
{
if (ar.length % 2 == 1)
return false ;
let hm = new Map();
for (let i = 0; i < ar.length; i++) {
let rem = ((ar[i] % k) + k) % k;
if (!hm.has(rem)) {
hm.set(rem, 0);
}
hm.set(rem, hm.get(rem) + 1);
}
for (let i = 0; i < ar.length; i++) {
let rem = ((ar[i] % k) + k) % k;
if (2 * rem == k) {
if (hm.get(rem) % 2 == 1)
return false ;
}
else if (rem == 0) {
if (hm.get(rem) % 2 == 1)
return false ;
}
else {
if (hm.get(k - rem) != hm.get(rem))
return false ;
}
}
return true ;
}
let arr = [ 92, 75, 65, 48, 45, 35 ];
let k = 10;
let ans = canPairs(arr, k);
if (ans)
document.write( "True" );
else
document.write( "False" );
</script>
|
Time complexity: O(n).
Auxiliary Space: O(n)
MOST OPTIMIZED SOLUTION:
Algorithm:
- In this approach we focus on the fact that if sum of two numbers mod K gives the output 0,then it is true for all instances that the individual number mod K would sum up to the K.
- We make an array of size K and there we increase the frequency and reduces it, if found a match and in the end if array has no element greater than 0 then it returns true else return false.
C++
#include <bits/stdc++.h>
using namespace std;
bool canPairs(vector< int > nums, int k) {
if (nums.size() % 2 != 0)
return false ;
vector< int > freq(k);
for ( int i : nums) {
int y = i % k;
if (freq[(k - y) % k] != 0)
freq[(k - y) % k]--;
else
freq[y]++;
}
for ( int i : freq) {
if (i != 0)
return false ;
}
return true ;
}
int main() {
vector< int > arr = {92, 75, 65, 48, 45, 35};
int k = 10;
if (canPairs(arr,k)) {
cout << "True" ;
} else {
cout << "False" ;
}
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
public static boolean canPairs( int [] nums, int k)
{
if (nums.length % 2 != 0 )
return false ;
int freq[] = new int [k];
for ( int i : nums) {
int y = i % k;
if (freq[(k - y) % k] != 0 )
freq[(k - y) % k]--;
else
freq[y]++;
}
for ( int i : freq) {
if (i != 0 )
return false ;
}
return true ;
}
public static void main(String[] args)
{
int arr[] = { 92 , 75 , 65 , 48 , 45 , 35 };
int k = 10 ;
if (canPairs(arr,k)) {
System.out.println( "True" );
}
else {
System.out.println( "False" );
}
}
}
|
C#
using System;
using System.Linq;
using System.Collections;
public class GFG {
public static bool canPairs( int [] nums, int n, int k)
{
if (nums.length % 2 != 0)
return false ;
int freq[] = new int [k];
for ( int i = 0; i < nums.length; i++) {
int y = nums[i] % k;
if (freq[(k - y) % k] != 0)
freq[(k - y) % k]--;
else
freq[y]++;
}
for ( int i = 0; i < freq.length; i++) {
if (freq[i] != 0)
return false ;
}
return true ;
}
public static void Main(String[] args)
{
int [] arr = { 92, 75, 65, 48, 45, 35 };
var k = 10;
var n = arr.Length;
if (GFG.canPairs(arr, n, k)) {
Console.WriteLine( "True" );
}
else {
Console.WriteLine( "False" );
}
}
}
|
Javascript
function canPairs(nums, k) {
if (nums.length % 2 !== 0)
return false ;
let freq = new Array(k).fill(0);
for (let i of nums) {
let y = i % k;
if (freq[(k - y) % k] !== 0)
freq[(k - y) % k]--;
else
freq[y]++;
}
for (let i of freq) {
if (i !== 0)
return false ;
}
return true ;
}
let arr = [92, 75, 65, 48, 45, 35];
let k = 10;
if (canPairs(arr, k)) {
console.log( "True" );
} else {
console.log( "False" );
}
|
- Time complexity: O(n),since every element is traversed for one time.
- Auxiliary Space: O(k),since array size will be k because it wont exceed k because we doing result mod k.
This article is contributed by Aarti_Rathi and Priyanka. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.