
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if an array can be divided into pairs whose sum is divisible by k in Python
Check if Array Can Be Divided into Pairs with Sum Divisible by K
In this article, we are given an array of integers and a number k. The task is to determine whether it is possible to divide the entire array into pairs such that the sum of every pair is divisible by k.
For example, if the given array of integers is [2, 4, 1, 3], and a value k = 5. The task is to form pairs (two elements at a time) from the array such that when you add each pair, the result is divisible by 5. In this case:
Pair (2, 3) -> 2 + 3 = 5 Pair (4, 1) -> 4 + 1 = 5 Explanation: All these pairs add up to values divisible by 5, so it returns true as a result.
Algorithm to Solve the Problem
The following is the algorithm to solve this task:
- Step 1: Check if the array has an even number of elements.
- Step 2: Then, create a dictionary to count remainders.
- Step 3: Count the remainders of each element.
- Step 4: Checking if all the valid pairs are formed.
- Step 5: Handling the special case where the remainder.
- Step 6: Check if the remainder and its complement have the same count.
- Step 7: If all checks pass, return True.
Example 1
In the following example, we are going to consider the array as [2,4,1,3] and k=5 and check if the array can be divided into pairs whose sum is divisible by k:
from collections import defaultdict def demo(array, k): # Step 1 if len(array) % 2 != 0: return False # Step 2 x = defaultdict(int) # Step 3 for num in array: remainder = num % k x[remainder] += 1 # Step 4 for rem in x: comp = (k - rem) % k # Step 5 if rem == 0: if x[rem] % 2 != 0: return False # Step 6 else: if x[rem] != x[comp]: return False # Step 7 return True array = [2,4,1,3] k = 5 print(demo(array, k))
Following is the output of the above program:
True
Example 2
Consider the following example, where we are going to consider the array = [1,2,3,4,5], k=4, and observing the output, which gives false because the length of the array is odd (which is impossible to make a pair).
from collections import defaultdict def demo(array, k): # Step 1 if len(array) % 2 != 0: return False # Step 2 x = defaultdict(int) # Step 3 for num in array: remainder = num % k x[remainder] += 1 # Step 4 for rem in x: comp = (k - rem) % k # Step 5 if rem == 0: if x[rem] % 2 != 0: return False # Step 6 else: if x[rem] != x[comp]: return False # Step 7 return True array = [1, 2, 3, 4, 5] k = 4 print(demo(array, k))
If we run the above program, it will generate the following output:
False