
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 Array Can Be Divided Into Pairs Divisible by K in Python
Suppose we have an array of numbers and have another number k, we have to check whether given array can be divided into pairs such that the sum of every pair is divisible by k or not.
So, if the input is like arr = [5, 15, 6, 9] k = 7, then the output will be True as we can take pairs like (5, 9) and (15, 6).
To solve this, we will follow these steps −
- n := size of array
- if n is odd, then
- return False
- occurrences := an empty dictionary, if some key is not there return 0 as the value of that missing key
- for i in range 0 to n, do
- increase occurrences[((array[i] mod k) + k) mod k] by 1
- for i in range 0 to n, do
- remainder := ((array[i] mod k) + k) mod k
- if 2 * remainder is same as k, then
- if occurrences[remainder] is odd, then
- return False
- if occurrences[remainder] is odd, then
- otherwise when remainder is same as 0, then
- if occurrences[remainder] AND 1 is non-zero, then
- return False
- if occurrences[remainder] AND 1 is non-zero, then
- otherwise when occurrences[remainder] is not same as occurrences[k - remainder], then
- return False
- return True
Let us see the following implementation to get better understanding −
Example
from collections import defaultdict def solve(array, k): n = len(array) if n % 2 != 0: return False occurrences = defaultdict(lambda : 0) for i in range(0, n): occurrences[((array[i] % k) + k) % k] += 1 for i in range(0, n): remainder = ((array[i] % k) + k) % k if (2 * remainder == k): if (occurrences[remainder] % 2 != 0): return False elif (remainder == 0): if (occurrences[remainder] & 1): return False elif (occurrences[remainder] != occurrences[k - remainder]): return False return True arr = [5, 15, 6, 9] k = 7 print(solve(arr, k))
Input
[5, 15, 6, 9], 7
Output
True
Advertisements