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 −
Let us see the following implementation to get better understanding −
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))
[5, 15, 6, 9], 7