Back to course home
0% completed
Vote For New Content
Iterations can be divided by 2
Fabrice L
May 29, 2024
You don't need to iterate over the entire array, you can just get half of it and retrieve values from the 4 "corners", and then add the middle point in case of a odd number of rows.
class Solution { diagonalSum(mat) { let totalSum = 0; // Initialize the total sum const len = mat.length; for (let i = 0; i < Math.floor(len / 2); i += 1) { totalSum += ( mat[i][i] + mat[i][len - 1 - i] + mat[len - 1 - i][i] + mat[len - 1 - i][len - 1 - i] ); } if (len % 2 === 1) { // add center let pt = Math.floor(len / 2); totalSum += mat[pt][pt]; } return totalSum; // Return the calculated total sum } }
0
0
Comments
Comments
On this page