Home > Software design >  Diagonal Difference In Matrix
Diagonal Difference In Matrix

Time:08-03

I Was trying to solve this question on hackerrank
https://www.hackerrank.com/challenges/diagonal-difference/problem?isFullScreen=true&h_r=next-challenge&h_v=zen

Using this algo

 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);
    }

}

For inputs like
1 2 3
4 5 6
9 8 9

It should give 2 as the answer but it is returning 34 IDK why?

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