• + 0 comments

    Here is my c++ solution, you can whatch the explanation here: https://youtu.be/aDv1iUSgnd8

    Solution 1 : O(n^2)

    int divisibleSumPairs(int n, int k, vector<int> ar) {
        int result = 0;
        for(int i = 0; i < ar.size() - 1; i++){
            for(int j = i + 1; j < ar.size(); j++){
                if( (ar[i] + ar[j]) % k == 0) result++;
            }
        }
        return result;
    }
    

    Solution 2 : O(n)

    int divisibleSumPairs(int n, int k, vector<int> ar) {
        map<int, int> mp;
        for(int i = 0; i < ar.size(); i++){
            mp[ar[i] % k]++;
        }
        int result = 0;
         for(int i = 0; i <= k/2; i++){
            if(i == 0 || i*2 == k) result += (mp[i] * (mp[i] - 1)) / 2;
            else result += mp[i] * mp[k - i]; 
        }
        return result;
    }