In this Diagonal Difference HackerRank Problem, Given a square matrix, calculate the absolute difference between the sums of its diagonals.
For example, the square matrix is shown below:
1 2 3
4 5 6
9 8 9
The left-to-right diagonal = . The right to left diagonal = . Their absolute difference is .
Function description
Complete the function in the editor below.
diagonalDifference takes the following parameter:
- int arr[n][m]: an array of integers
Return
- int: the absolute diagonal difference
Input Format
The first line contains a single integer, , the number of rows and columns in the square matrix .
Each of the next lines describes a row, , and consists of space-separated integers .
Constraints
Output Format
Return the absolute difference between the sums of the matrix’s two 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
Note: |x| is the absolute value of x
Diagonal Difference Hacker Rank Problem Solutions
I will Provide solution in Multiple programming languages for you. If you are not able to find the code in required language then please share in comments so that our team can help you.
Problem Solution in Python
def diagonalDifference(arr):
n = len(arr)-1
a = 0
b = 0
for i in range(len(arr)):
a+=arr[i][i]
b+=arr[i][n-i]
return abs(a-b)
Problem Solution in C++
int diagonalDifference(vector<vector<int>> arr) {
int num1=0;
int num2=0;
int n = arr.size();
int m = arr[0].size();
int index = 0;
int index2 = m-1;
for(int i = 0; i < n; i++) {
num1 += arr[i][index];
index++;
num2 += arr[i][index2];
index2--;
}
return abs(num1-num2);
}
Problem Solution in Java
public static int diagonalDifference(int n, List<List<Integer>> arr) {
int pdIdx = 0;
int sdIdx = n-1;
int primaryDiagonal = 0;
int secondaryDiagonal = 0;
while(sdIdx > -1)
{
primaryDiagonal += arr.get(pdIdx).get(pdIdx);
secondaryDiagonal += arr.get(pdIdx).get(sdIdx);
sdIdx--;
pdIdx++;
}
return Math.abs(primaryDiagonal-secondaryDiagonal);
}
Problem Solution in JavaScript
function diagonalDifference(arr) {
let diagonal1 = 0, diagonal2 = 0;
for (let i = 0; i < arr.length; i++) {
diagonal1 += arr[i][i];
diagonal2 += arr[i][arr.length - 1 - i];
}
return Math.abs(diagonal1 - diagonal2);
}
Leave a Reply