Check If Array Pairs Are Divisible by k Problem
Description
LeetCode Problem 1497.
Given an array of integers arr of even length n and an integer k.
We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k.
Return true If you can find a way to do that or false otherwise.
Example 1:
Input: arr = [1,2,3,4,5,10,6,7,8,9], k = 5
Output: true
Explanation: Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).
Example 2:
Input: arr = [1,2,3,4,5,6], k = 7
Output: true
Explanation: Pairs are (1,6),(2,5) and(3,4).
Example 3:
Input: arr = [1,2,3,4,5,6], k = 10
Output: false
Explanation: You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.
Constraints:
arr.length == n1 <= n <= 10^5nis even.-10^9 <= arr[i] <= 10^91 <= k <= 10^5
Solution
Approach: Count Remainders
Whether a + b is divisible by k depends only on the remainders a mod k and b mod k: they must add up to 0 or to k. So we only need to count how many numbers have each remainder r in 0..k-1, in an array cnt.
- A number with remainder
0can only pair with another number with remainder0, socnt[0]must be even. - A number with remainder
r(for1 <= r < k) can only pair with remainderk - r, socnt[r] == cnt[k - r]must hold for every suchr. Whenkis even,r = k / 2pairs with itself and the check comparescnt[k/2]with itself; since the total count is even and every other group pairs up evenly,cnt[k/2]is then even too.
If all of these hold, we can build the pairs group by group, so the answer is true.
The tricky part is negative numbers: in Java, C++, JavaScript and Go, -3 % 5 is -3, not 2. Use (x % k + k) % k to get a remainder in 0..k-1. Python's % is already non-negative.
Complexity: O(n + k) time and O(k) space.
class Solution:
def canArrange(self, arr: List[int], k: int) -> bool:
cnt = [0] * k # cnt[r]: how many numbers leave remainder r (Python's % is never negative)
for x in arr:
cnt[x % k] += 1
if cnt[0] % 2:
return False
return all(cnt[r] == cnt[k - r] for r in range(1, k))