Check if an array can be divided into pairs whose sum is divisible by k
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++
// A C++ program to check if arr[0..n-1] // can be divided in pairs such that // every pair is divisible by k #include <bits/stdc++.h> using namespace std; bool canPairs( int nums[], int n, int k) { // Array with odd length // cannot be divided if (n % 2 == 1) return false ; // Initialize count = 0 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) { // if pair is divisible increment // the count and mark elements // as visited count++; vis[i] = 1; vis[j] = 1; } } } if (count == n / 2) return true ; else return false ; } // Driver code int main() { int arr[] = { 92, 75, 65, 48, 45, 35 }; int k = 10; int n = sizeof (arr) / sizeof (arr[0]); // Function call canPairs(arr, n, k) ? cout << "True" : cout << "False" ; return 0; } // This code is contributed by Arpit Jain |
Java
/*package whatever //do not write package name here */ import java.util.*; class GFG { static boolean canPairs( int nums[], int n, int k) { // Array with odd length // cannot be divided if (n % 2 == 1 ) return false ; // Initialize count = 0 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 ) { // if pair is divisible increment // the count and mark elements // as visited 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; // Function call if (canPairs(arr, n, k)){ System.out.println( "True" ); } else { System.out.println( "False" ); } } } // This code is contributed by aadityaburujwale. |
Python3
# A Python3 program to check if arr[0..n-1] # can be divided in pairs such that # every pair is divisible by k def canPairs(nums, n, k): # Array with odd length # cannot be divided if (n % 2 = = 1 ): return False # Initialize count = 0 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 ): # if pair is divisible increment # the count and mark elements # as visited count + = 1 vis[i] = 1 vis[j] = 1 if (count = = n / 2 ): return True else : return False # Driver code arr = [ 92 , 75 , 65 , 48 , 45 , 35 ] k = 10 n = len (arr) # Function call if (canPairs(arr, n, k)): print ( "True" ) else : print ( "False" ) # This code is contributed by akashish__ |
C#
// Include namespace system using System; using System.Linq; using System.Collections; public class GFG { public static bool canPairs( int [] nums, int n, int k) { // Array with odd length // cannot be divided if (n % 2 == 1) { return false ; } // Initialize count = 0 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) { // if pair is divisible increment // the count and mark elements // as visited 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; // Function call if (GFG.canPairs(arr, n, k)) { Console.WriteLine( "True" ); } else { Console.WriteLine( "False" ); } } } // This code is contributed by aadityaburujwale. |
Javascript
// Javascript program to check if arr[0..n-1] // can be divided in pairs such that // every pair is divisible by k function canPairs(nums, n, k) { // Array with odd length // cannot be divided if (n % 2 === 1) return false ; // Initialize count = 0 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) { // if pair is divisible increment // the count and mark elements // as visited count++; vis[i] = 1; vis[j] = 1; } } } if (count === n / 2) return true ; else return false ; } // Driver code var arr = [ 92, 75, 65, 48, 45, 35 ]; var k = 10; var n = arr.length; // Function call canPairs(arr, n, k) ? console.log( "True" ) : console.log( "False" ); // This code is contributed by Abhijeet Kumar(abhijeet19403) |
True
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++
// A C++ program to check if arr[0..n-1] can be divided // in pairs such that every pair is divisible by k. #include <bits/stdc++.h> using namespace std; // Returns true if arr[0..n-1] can be divided into pairs // with sum divisible by k. bool canPairs( int arr[], int n, int k) { // An odd length array cannot be divided into pairs if (n & 1) return false ; // Create a frequency array to count occurrences // of all remainders when divided by k. unordered_map< int , int > freq; // Count occurrences of all remainders for ( int i = 0; i < n; i++) freq[((arr[i] % k) + k) % k]++; // Traverse input array and use freq[] to decide // if given array can be divided in pairs for ( int i = 0; i < n; i++) { // Remainder of current element int rem = ((arr[i] % k) + k) % k; // If remainder with current element divides // k into two halves. if (2 * rem == k) { // Then there must be even occurrences of // such remainder if (freq[rem] % 2 != 0) return false ; } // If remainder is 0, then there must be even // number of elements with 0 remainder else if (rem == 0) { if (freq[rem] & 1) return false ; } // Else number of occurrences of remainder // must be equal to number of occurrences of // k - remainder else if (freq[rem] != freq[k - rem]) return false ; } return true ; } // Driver code int main() { int arr[] = { 92, 75, 65, 48, 45, 35 }; int k = 10; int n = sizeof (arr) / sizeof (arr[0]); // Function call canPairs(arr, n, k) ? cout << "True" : cout << "False" ; return 0; } |
Java
// JAVA program to check if arr[0..n-1] can be divided // in pairs such that every pair is divisible by k. import java.util.HashMap; public class Divisiblepair { // Returns true if arr[0..n-1] can be divided into pairs // with sum divisible by k. static boolean canPairs( int ar[], int k) { // An odd length array cannot be divided into pairs if (ar.length % 2 == 1 ) return false ; // Create a frequency array to count occurrences // of all remainders when divided by k. HashMap<Integer, Integer> hm = new HashMap<>(); // Count occurrences of all remainders 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 ); } // Traverse input array and use freq[] to decide // if given array can be divided in pairs for ( int i = 0 ; i < ar.length; i++) { // Remainder of current element int rem = ((ar[i] % k) + k) % k; // If remainder with current element divides // k into two halves. if ( 2 * rem == k) { // Then there must be even occurrences of // such remainder if (hm.get(rem) % 2 == 1 ) return false ; } // If remainder is 0, then there must be two // elements with 0 remainder else if (rem == 0 ) { // Then there must be even occurrences of // such remainder if (hm.get(rem) % 2 == 1 ) return false ; } // Else number of occurrences of remainder // must be equal to number of occurrences of // k - remainder else { if (hm.get(k - rem) != hm.get(rem)) return false ; } } return true ; } // Driver code public static void main(String[] args) { int arr[] = { 92 , 75 , 65 , 48 , 45 , 35 }; int k = 10 ; // Function call boolean ans = canPairs(arr, k); if (ans) System.out.println( "True" ); else System.out.println( "False" ); } } // This code is contributed by Rishabh Mahrsee |
Python3
# Python3 program to check if # arr[0..n-1] can be divided # in pairs such that every # pair is divisible by k. from collections import defaultdict # Returns true if arr[0..n-1] can be # divided into pairs with sum # divisible by k. def canPairs(arr, n, k): # An odd length array cannot # be divided into pairs if (n & 1 ): return 0 # Create a frequency array to # count occurrences of all # remainders when divided by k. freq = defaultdict( lambda : 0 ) # Count occurrences of all remainders for i in range ( 0 , n): freq[((arr[i] % k) + k) % k] + = 1 # Traverse input array and use # freq[] to decide if given array # can be divided in pairs for i in range ( 0 , n): # Remainder of current element rem = ((arr[i] % k) + k) % k # If remainder with current element # divides k into two halves. if ( 2 * rem = = k): # Then there must be even occurrences # of such remainder if (freq[rem] % 2 ! = 0 ): return 0 # If remainder is 0, then there # must be two elements with 0 remainder else if (rem = = 0 ): if (freq[rem] & 1 ): return 0 # Else number of occurrences of # remainder must be equal to # number of occurrences of # k - remainder else if (freq[rem] ! = freq[k - rem]): return 0 return 1 # Driver code arr = [ 92 , 75 , 65 , 48 , 45 , 35 ] k = 10 n = len (arr) # Function call if (canPairs(arr, n, k)): print ( "True" ) else : print ( "False" ) # This code is contributed by Stream_Cipher |
C#
// C# program to check if arr[0..n-1] // can be divided in pairs such that // every pair is divisible by k. using System.Collections.Generic; using System; class GFG { // Returns true if arr[0..n-1] can be // divided into pairs with sum // divisible by k. static bool canPairs( int [] ar, int k) { // An odd length array cannot // be divided into pairs if (ar.Length % 2 == 1) return false ; // Create a frequency array to count // occurrences of all remainders when // divided by k. Dictionary<Double, int > hm = new Dictionary<Double, int >(); // Count occurrences of all remainders for ( int i = 0; i < ar.Length; i++) { int rem = ((ar[i] % k) + k) % k; if (!hm.ContainsKey(rem)) { hm[rem] = 0; } hm[rem]++; } // Traverse input array and use freq[] // to decide if given array can be // divided in pairs for ( int i = 0; i < ar.Length; i++) { // Remainder of current element int rem = ((ar[i] % k) + k) % k; // If remainder with current element // divides k into two halves. if (2 * rem == k) { // Then there must be even occurrences // of such remainder if (hm[rem] % 2 == 1) return false ; } // If remainder is 0, then there // must be two elements with 0 // remainder else if (rem == 0) { // Then there must be even occurrences // of such remainder if (hm[rem] % 2 == 1) return false ; } // Else number of occurrences of remainder // must be equal to number of occurrences of // k - remainder else { if (hm[k - rem] != hm[rem]) return false ; } } return true ; } // Driver code public static void Main() { int [] arr = { 92, 75, 65, 48, 45, 35 }; int k = 10; // Function call bool ans = canPairs(arr, k); if (ans) Console.WriteLine( "True" ); else Console.WriteLine( "False" ); } } // This code is contributed by Stream_Cipher |
Javascript
<script> // Javascript program to check if arr[0..n-1] can be divided // in pairs such that every pair is divisible by k. // Returns true if arr[0..n-1] can be divided into pairs // with sum divisible by k. function canPairs(ar, k) { // An odd length array cannot be divided into pairs if (ar.length % 2 == 1) return false ; // Create a frequency array to count occurrences // of all remainders when divided by k. let hm = new Map(); // Count occurrences of all remainders 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); } // Traverse input array and use freq[] to decide // if given array can be divided in pairs for (let i = 0; i < ar.length; i++) { // Remainder of current element let rem = ((ar[i] % k) + k) % k; // If remainder with current element divides // k into two halves. if (2 * rem == k) { // Then there must be even occurrences of // such remainder if (hm.get(rem) % 2 == 1) return false ; } // If remainder is 0, then there must be two // elements with 0 remainder else if (rem == 0) { // Then there must be even occurrences of // such remainder if (hm.get(rem) % 2 == 1) return false ; } // Else number of occurrences of remainder // must be equal to number of occurrences of // k - remainder else { if (hm.get(k - rem) != hm.get(rem)) return false ; } } return true ; } // Driver program let arr = [ 92, 75, 65, 48, 45, 35 ]; let k = 10; // Function call let ans = canPairs(arr, k); if (ans) document.write( "True" ); else document.write( "False" ); </script> |
True
Time complexity: O(n).
Auxiliary Space: O(n)
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.
Please Login to comment...