Check if an array can be divided into pairs whose sum is 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
    • otherwise when remainder is same as 0, then
      • if occurrences[remainder] AND 1 is non-zero, then
        • return False
    • 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

 Live Demo

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

Updated on: 30-Dec-2020

119 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements