Given a square matrix, calculate the absolute difference between the sums of its diagonals.
The most efficient way is to approach this is to implement a solution running linearly achieving the 0(n).
We will create a method sumOfDiagonals which takes in a parameter arr: Array<IntArray>. This allows us to create a 2D array. Create variables leftToRight, rightToLeft which will be equal to 0 representing the diagonal lines. Variable rows equal to the size of the array arr.size and columns equal to the size of the positions arr[0].size.
Create the counters for the positions and assert them to 0. var i = 0, var j = 0, var k = 0, var l = arr.size - 1 this a right to left column counter.
Create a while loop that checks the rows and column counters and if the value is satisfied it should increment the counters and add the leftToRight, rightToLeft values together.
To make it work return the absolute difference return Math.abs(leftToRight - rightToLeft).
Easy Peasy, Lemon Squeezy 😄 😄.
Let's look at the code
fun sumOfDiagonals(arr: Array<IntArray>): Int {
var leftToRight = 0
var rightToLeft = 0
val rows = arr.size
val columns = arr[0].size
var i = 0
var j = 0
var k = 0
var l = arr.size - 1 //right to left column counter
while (rows >= 0 && columns >= 0 && rows >= 0 && l >= 0) {
leftToRight += arr[i][j] //add the values at the position
rightToLeft += arr[k][l] //add the values at the position
i += 1
j += 1
k += 1
l -= 1
}
return abs(leftToRight - rightToLeft) ///return the difference
}
Thank you for reading, please share if you found it helpful 💯.
Asante Sana
Top comments (0)