Home > Net >  Diagonal Difference in a Matrix
Diagonal Difference in a Matrix

Time:08-03

I was trying to solve this problem on Hackerrank:

Given a square matrix, calculate the absolute difference between the sums of its diagonals.

My code:

 public static int diagonalDifference(List<List<Integer>> arr) {
    // Write your code here
    int d1=0;
    int d2=0;
    for(int i=0;i<arr.size();i  )
    {
        for(int j=0;j<arr.get(i).size();j  )
        {
            if(i==j)
            {
                d1=d1 arr.get(i).get(j);
            }
            if((i j)==arr.size()-1);
            {
                d2=d2 arr.get(i).get(j);
            }
        }
    }
    int ans =d1-d2;
    return Math.abs(ans);
    }
}

The following input

1 2 3
4 5 6
9 8 9

Should produce the output of 2, but my code gives 34. Can anyone explain why does that happens?

CodePudding user response:

The problem you are having is a stray semicolon:

        // right here----------v
        if((i j)==arr.size()-1);
        {
            d2=d2 arr.get(i).get(j);
        }

Removing it should get you the correct answer of "2"

CodePudding user response:

Given a square matrix, calculate the absolute difference between the sums of its diagonals.

Since according to the description, we are given a square matrix, there's no need of creating a nested loop. And we can get rid of if-statements as well.

The code can be simplified to:

public static int diagonalDifference(List<List<Integer>> arr) {
    int d1 = 0;
    int d2 = 0;
    
    for (int i = 0; i < arr.size(); i  ) {
        d1  = arr.get(i).get(i);
        d2  = arr.get(arr.size() - 1 - i).get(i);
    }
    
    return Math.abs(d1 - d2);
}

This solution passes all test cases.

  • Related