Search code examples
javaarraysalgorithmreturn

I can't run all my test cases correctly, what's wrong?


Complete the divisibleSumPairs function in the editor below. It should return the integer count of pairs meeting the criteria.

divisibleSumPairs has the following parameter(s):

  • n: the integer length of array ar

  • ar: an array of integers

  • k: the integer to divide the pair sum by

Print the number of (i, j) pairs where i < j and ar[i] + ar[j] is evenly divisible by k.

I don't know what is wrong, only some cases has worked

  static int divisibleSumPairs(int n, int k, int[] ar) {
    int count = 0;
    for (int i=0; i<n; i++){
        for (int j=0; j<n; j++){
            if ((ar[i]<ar[j]) && ((ar[i]+ar[j])%k)== 0){
                count++;
            }
        }
    }
        return count;
}

Solution

  • The main problem is that you check for ar[i] < ar[j] while the problem statement says i < j:

    static int divisibleSumPairs(int n, int k, int[] ar) {
        int count = 0;
        for (int i = 0; i < n; i++){
            for (int j = 0; j < n; j++){
                if (i < j && (ar[i] + ar[j]) % k == 0) {
                    count++;
                }
            }
        }
        return count;
    }
    

    The algorithm can be further optimized to:

    static int divisibleSumPairs(int n, int k, int[] ar) {
        int count = 0;
        for (int i = 0; i < n; i++){
            for (int j = i + 1; j < n; j++){
                if ((ar[i] + ar[j]) % k == 0) {
                    count++;
                }
            }
        }
        return count;
    }