Skip to content
Advertisement

What does it mean by “second += arr[i][arr.length-i-1]”

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:

JavaScript

and the solution is like this:

JavaScript

So, I came up with this solution:

JavaScript

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.

Advertisement