Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Code : Check If Array Pairs Are Divisible by k

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    bool canArrange(vector<int> &arr, int k);
};

bool Solution::canArrange(vector<int> &a, int k) {
    int n = a.size();

    vector<int> rem_freq(k);

    // Handle negative modulo.
    for (int i = 0; i < n; i++) {
        int mod = a[i] % k;
        mod = (mod + k) % k;
        rem_freq[mod]++;
    }

    // We don't need to worry about rem_freq[0]. If it is odd, the for loop
    // would eventually fail some check.
    for (int i = 1; i < k; i++) {
        int comp = k - i;
        if (i == comp && rem_freq[i] % 2 != 0) {
            return false;
        } else if (rem_freq[i] != rem_freq[comp]) {
            return false;
        }
    }
    return true;
}