Check If Array Pairs Are Divisible by k

medium hash map modular arithmetic

Problem

You are given an integer array arr whose length n is even, and a positive integer k. Decide whether the whole array can be split into exactly n / 2 pairs so that the sum of every pair is divisible by k. Each element must belong to exactly one pair, and values may be negative.

Return true if such a complete pairing exists, otherwise false.

Inputarr = [1,2,3,4,5,10,6,7,8,9], k = 5
Outputtrue
Pairs (1,9), (2,8), (3,7), (4,6), (5,10) each sum to a multiple of 5.

def can_arrange(arr, k):
    count = [0] * k
    for x in arr:
        count[x % k] += 1   # Python % is already non-negative
    if count[0] % 2 != 0:
        return False
    for r in range(1, k // 2 + 1):
        if count[r] != count[k - r]:
            return False
    return True
function canArrange(arr, k) {
  const count = new Array(k).fill(0);
  for (const x of arr) {
    count[((x % k) + k) % k]++;
  }
  if (count[0] % 2 !== 0) return false;
  for (let r = 1; r <= Math.floor(k / 2); r++) {
    if (count[r] !== count[k - r]) return false;
  }
  return true;
}
boolean canArrange(int[] arr, int k) {
    int[] count = new int[k];
    for (int x : arr) {
        count[((x % k) + k) % k]++;
    }
    if (count[0] % 2 != 0) return false;
    for (int r = 1; r <= k / 2; r++) {
        if (count[r] != count[k - r]) return false;
    }
    return true;
}
bool canArrange(vector<int>& arr, int k) {
    vector<int> count(k, 0);
    for (int x : arr) {
        count[((x % k) + k) % k]++;
    }
    if (count[0] % 2 != 0) return false;
    for (int r = 1; r <= k / 2; r++) {
        if (count[r] != count[k - r]) return false;
    }
    return true;
}
Time: O(n + k) Space: O(k)