Member-only story

Coding Interview Prep: Find the Diagonal Difference of a Square Matrix

Marika Lam
Jun 26, 2024

--

Prompt

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

Solution

Here we loop through array. Because it is always a square matrix, we can get arr[i][i] to sum for both diaganols. Math.abs() is an important math function to get the absolute value of the difference of the diaganols.

function diagonalDifference(arr) {
let sum1 = 0;
let sum2 = 0;

for (let i=0; i<arr.length; i++){
sum1+=arr[i][i];
sum2+=arr[arr.length-i-1][i];
}

return Math.abs(sum1-sum2);
}

--

--

No responses yet