I been practicing my algorithm solving skill by solving HackerRank problems. However, one of the problems is giving me a difficult time to understand. It is about calculating absolute difference between sum of diagonals in a square matrix “arr”.
If the square matrix is like this:
1 2 3 4 5 6 5 2 4
and the solution is like this:
1st diagonal = 1 + 5 + 4 = 10 2nd diagonal = 3 + 5 + 5 = 13 difference = |10 - 13| = 3 <-- This should appear!
So, I came up with this solution:
function diagonalDifference(arr) { let first = 0; let second = 0; let diff = 0; for(let i = 0; i < arr.length; i++){ first += arr[i][i]; second += arr[i][arr.length-i-1] } diff = first - second; return Math.abs(diff); }
However, I figure out all other parts except the “second += arr[i][arr.length-i-1]” part. I don’t understand what [arr.length-i-1] is doing. Help me understand this.
Advertisement
Answer
When i
starts at 0, arr.length - i - 1
starts at the last index in the array and iterates backwards towards the beginning. So, for example, if there are 4 elements, it’ll access index [3]
, then [2]
, then [1]
, then [0]
.
For this problem, the array of arrays is square. arr[i][arr.length - i - 1]
will result in arr[0][2]
, then arr[1][1]
, then arr[2][0]
– which is the diagonal from the top right to the bottom left (which the problem is asking you to calculate).
If there were 5 subarrays, the indicies iterated over would be arr[0][4]
, arr[1][3]
, arr[2][2]
, arr[3][1]
, arr[4][0]
. And so on.