# HackerRank Challenges: Diagonal Difference

I love HackerRank, its a web app where you can complete challenges to get better at coding, and i think i’ll start a new series here on the blog covering some of the implementations that i made to some challenges.

This one is about the Diagonal Difference, here’s the challenge:

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

Input Format

The first line contains a single integer, N. The next 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

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

So i came up with this code for Java:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int a[][] = new int[n][n];
int sum_primary_diagonal = 0;
int sum_secondary_diagonal = 0;
int absolute_difference_of_diagonals = 0;
for(int a_i=0; a_i < n; a_i++){
for(int a_j=0; a_j < n; a_j++){
a[a_i][a_j] = in.nextInt();

// logic for diagonal
if (a_i == a_j) {
sum_primary_diagonal = sum_primary_diagonal + a[a_i][a_j];
}

// logic for reverse diagonal
if(a_i + a_j == n-1)
sum_secondary_diagonal = sum_secondary_diagonal + a[a_i][a_j];
}
}
absolute_difference_of_diagonals = Math.abs(sum_primary_diagonal - sum_secondary_diagonal);
System.out.println(absolute_difference_of_diagonals);
}

}


You can check out this challenge here. Please tell me in the comments if there’s a more efficient way, or even a better way to do it!

• Hannah Akinyi

Thanks for this 🙂