Suppose we have a list of numbers called nums and another value k, we have to check whether the list can be partitioned into pairs such that the sum of each pair is divisible by k.
So, if the input is like nums = [4, 7, 2, 5] k = 6, then the output will be True, as we can partition the given list into pairs like (4, 2) and (8, 1) and their sums are divisible by 3.
To solve this, we will follow these steps:
- if nums has even number of elements, then
- return False
- count := a list of size k and fill with 0
- for each n in nums, do
- count[n mod k] := count[n mod k] + 1
- if count[0] is even, then
- return False
- for i in range 1 to quotient of (k / 2), do
- if count[i] is not same as count[k - i], then
- return False
- if count[i] is not same as count[k - i], then
- return True
Let us see the following implementation to get better understanding:
Example
class Solution: def solve(self, nums, k): if len(nums) % 2: return False count = [0] * k for n in nums: count[n % k] += 1 if count[0] % 2: return False for i in range(1, k // 2 + 1): if count[i] != count[k - i]: return False return True ob = Solution() nums = [4, 7, 2, 5] k = 6 print(ob.solve(nums, k))
Input
[4, 7, 2, 5], 6
Output
True