Skip to content

1497. Check If Array Pairs Are Divisible by k 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  bool canArrange(vector<int>& arr, int k) {
    vector<int> count(k);

    for (int a : arr) {
      a %= k;
      ++count[a < 0 ? a + k : a];
    }

    if (count[0] % 2 != 0)
      return false;

    for (int i = 1; i <= k / 2; ++i)
      if (count[i] != count[k - i])
        return false;

    return true;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public boolean canArrange(int[] arr, int k) {
    int[] count = new int[k];

    for (int a : arr) {
      a %= k;
      ++count[a < 0 ? a + k : a];
    }

    if (count[0] % 2 != 0)
      return false;

    for (int i = 1; i <= k / 2; i++)
      if (count[i] != count[k - i])
        return false;

    return true;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def canArrange(self, arr: list[int], k: int) -> bool:
    count = [0] * k

    for a in arr:
      a %= k
      count[a if a >= 0 else a + k] += 1

    return (count[0] % 2 == 0 and
            all(count[i] == count[k - i]
                for i in range(1, k // 2 + 1)))