JavaScript Coding Challenge #6 ~ Follow up
It’s very nice to see other solutions for these coding challenges I’ve been posting for the past few weeks. Honestly I learned a lot and this is why I wanted to share some of the solutions with you, by writing a little follow up on the Diagonal Difference problem I posted yesterday. Please check it out before you continue to have a grasp of what we’re going to do.
I wanted to thank John Swindin and @ksjazzguitar from the FreeCodeCamp forum for the little tip they both gave me.
My approach for adding up the sum of the elements of the second diagonal wasn’t that good. We can increase the performance of the algorithm from O(n * n) to O(n), by removing one for loop our previous solution. Amazing, right? Thank you guys for pointing that out! :D
First, let’s recap what was my approach for the second diagonal sum:
- loop through all the elements of the matrix
- if the sum of the indexes (
i + j) is equal to the length of the matrix minus one:i + j === n — 1 - add that number to the
diag2-> representing the total sum for the second diagonal
Good, but not the best… xD
What we can actually do is to kick out the second inner loop, because we don’t need it! Let’s implement modify that in code so we can understand better:
function calculateDiagonals(matrix){ var n = matrix.length;
var diag1 = 0;
var diag2 = 0; for(var i=0; i<n; i++){ }}
Because we have a square matrix of size: n * n, we’ll get the first diagonal sum by adding up elements from index: [i][i] and the second diagonal sum, as we saw above, by adding the elements from index: [i][n — i — 1].
Get Florin Pop’s stories in your inbox
Join Medium for free to get updates from this writer.
Why [n — i — 1]? Let’s see again a matrix with a size of 3 with the indexes:
(0, 0) (0, 1) (0, 2)
(1, 0) (1, 1) (1, 2)
(2, 0) (2, 1) (2, 2)Our for loop iterations we’ll give us for the second diagonal:
n = 3,i = 0=> we get the element(0, 3 — 0 — 1) = (0, 2)n = 3,i = 1=> we get the element(1, 3 — 1 — 1) = (1, 1)n = 3,i = 1=> we get the element(2, 3 — 2 — 1) = (2, 0)
This is exactly what we wanted! So the final code would be:
function calculateDiagonals(matrix){ var n = matrix.length;
var diag1 = 0;
var diag2 = 0; for(var i=0; i<n; i++){
diag1 += matrix[i][i];
diag2 += matrix[i][n - i - 1];
} return Math.abs(diag1 - diag2);
}
Awesome! This is way faster than what we had before! :)
Conclusion
Last year I was reading more about how to become a better chess player, and one of the great tips I’ve learned is that whenever you find a good move, hold on for a while and see if you can find a better move.
This is something we can use when we are programming. Even if your approach is good and the algorithm works, out there might be a better solution!
If you liked this follow up and if you found it useful, I would sincerely appreciate a click on the Recommend button 💚.









