#1497
Medium Algorithms Check if array pairs are divisible by k
Array Hash Table Counting
46.2% acceptance
Feb 25, 2026
2617
156
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.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn can_arrange(arr: Vec<i32>, k: i32) -> bool {
let k = k as i64;
let mut cnt = vec![0i64; k as usize];
for &x in &arr {
let r = ((x as i64 % k) + k) % k;
cnt[r as usize] += 1;
}
if cnt[0] % 2 != 0 { return false; }
for r in 1..=(k / 2) as usize {
if r == (k as usize - r) {
if cnt[r] % 2 != 0 { return false; }
} else if cnt[r] != cnt[k as usize - r] {
return false;
}
}
true
}
}