Diagonal Difference
Given a square matrix, calculate the absolute difference between the sums of its diagonals.
It is the most easiest problem from 1 month Interview Prep kit on HackerRank.
You would be provided a 2 dimensional array of equal rows and columns or a square matrix one might call as the input. The output that you have to produce would be the sum of one diagonal subtracted to sum of second diagonal.
[[1,2,3],[4,5,6],[9,8,9]]
Let us take the above 2-D array as the input.
1 2 3
4 5 6
9 8 9
The first diagonal would be [1, 5, 9] and their sum is 1+5+9=15;
The second diagonal would be [3, 5, 9] and their sum is 3+5+9=17;
Your output should be |15-17|=2; here '||' represents absolute function [You can read about absolute function by clicking the link].
The language used here is Javascript but you can use any language that you find comfortable to code in.
The thought process would be -
- Take a variable and assign a 2-D array to it
let array=[[1,2,3],[4,5,6],[9,8,9]];
Initialize and assign two variables to store sums of two diagonals
let sum1=0, sum2=0;
Use nested for loops to traverse through the square matrix
for(let i=0;i<array.length;i++) { for(let j=0;j<array.length;j++) { if(i===j) sum1+=arr[i][j]; if(i+j===array.length-1) sum2+=arr[i][j]; } }
The first if condition is to check for the first diagonal i.e. [1,5,9]; logic behind this is to position of 1 is array[0][0], position of 5 is array[1][1], position of 9 is array[2][2]. So to find the first diagonal, the condition is outer counter i should be equals to inner counter j.
The second if condition is to check for the second diagonal i.e. [3,5,9]; logic behind this is posItion of 3 is array[0][2] which is equal to 0+2 (2) and length of array, 3-1 (2) and same for 5 and 9.
Increment the sums of both diagonals.i===j //To check for first diagonal elements
i+j===array.length-1 //To check for second diagonal elementsInitialize and assign the variable to the difference of the sums of two diagonals' elements
let res=sum1-sum2;
Print the result by using a ternary operator or an if else condition; I have used a ternary operator here
console.log(res>0?res:-res);
The ternary operator here is equivalent to the following if else statement
if(res>0) console.log(res); else console.log(-res);
You can also use built in Math.abs() function.
This problem uses the concepts of 2-D array traversal and absolute function.