Hackerrank Solution: Diagonal Difference

Published on: 15th July 2016

This tutorial provides Java and Python solution to diagonal difference problem of Hackerrank.

# Hackerrank Challenge Details

**Problem Statement:**

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 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:**

```
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
```

# Solution Details

**Java Implementation:**

```
package com.saintech.allprogtutorials.hackerrank.algos;
import java.util.Scanner;
/**
* @author Sain Technology Solutions
*
* Solution to Problem - https://www.hackerrank.com/challenges/diagonal-difference
*/
public class DiagonalDifference {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
final int N = Integer.parseInt(in.nextLine());
long diff = 0;
for(int i=0; i < N; i++) {
String[] row = in.nextLine().split(" ");
diff += (Integer.parseInt(row[i]) - Integer.parseInt(row[N - 1 - i]));
}
System.out.println(Math.abs(diff));
in.close();
}
}
```

**Python Implementation:**

```
#!/bin/python
import sys
N = int(raw_input())
difference = 0
for i in xrange(N):
row = raw_input().split()
difference += (int(row[i]) - int(row[N-1-i]))
print abs(difference)
```

Thank you for reading through the tutorial. In case of any feedback/questions/concerns, you can communicate same to us through your comments and we shall get back to you as soon as possible.

Published on: 15th July 2016