Diagonal difference in Java

Problem: Given a square matrix of size N×N, calculate the absolute difference between the sums of its diagonals.
This question was asked in HackerRank. We will see a simple and elegent solution for this problem in Java.

Input format:
The first line contains a single integer, N. The next N lines denote the matrix’s rows, with each line containing N space-separated integers describing the columns.

Output format:
Print the absolute difference between the two sums of the matrix’s diagonals as a single integer.

Sample input:
3
11 2 4
4 5 6
10 8 -12

Sample output:
15

Explanation for diagonal difference:

The primary diagonal is:
11
5
-12
Sum across the primary diagonal: 11 + 5 – 12 = 4

The secondary diagonal is:
4
5
10
Sum across the secondary diagonal: 4 + 5 + 10 = 19
Difference: |4 – 19| = 15

Java code:
We will see how to find diagonal difference in Java.

import java.util.Scanner;

public class DiagonalDifference {
    
    private static int calculateDiagonalDifference(int[][] arr) {
        int len = arr.length;
        int leftDiagonalSum = 0;
        int rightDiagonalSum = 0;
        
        int index = 0;
        while(index < len) {
            leftDiagonalSum += arr[index][index];
            rightDiagonalSum += arr[index][len-1-index];
            index++;
        }
        
        return Math.abs(leftDiagonalSum - rightDiagonalSum);
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int arr[][] = new int[n][n];
        for(int i=0; i < n; i++){
            for(int j=0; j < n; j++){
                arr[i][j] = in.nextInt();
            }
        }
        in.close();
        System.out.println(calculateDiagonalDifference(arr));
    }
}

Analysis:
Above program has a run-time of Ο(n).
To calculate sum of right and left diagonal, we are running a loop n times. So run-time of algorithm is Ο(n).

I hope you liked the solution for diagonal difference.
Please comment for questions and doubts.

Leave a Reply