DEV Community

Nitin Sijwali
Nitin Sijwali

Posted on • Edited on

Javascript: Sum diagonal and counter diagonal elements of n * n matrix

Given a square matrix of size n, calculate the sum of diagonal and counter diagonal elements.
where n > 1

Example:
[
  [1, 8, 7],
  [2, 9, 6],
  [3, 4, 5]
]
diagonal = positions [0][0] + [1][1]+ [2][2] => 1+9+5 =15,
counterDiagonal = positions [0][2] + [1][1]+ [3][0] => 7+9+3 =19
Enter fullscreen mode Exit fullscreen mode

Let's try first with brute force method then will optimise it.

function sumOfDiagonals(matrix) {
  const len = matrix.length;
  let diagonalSum = 0;
  let counterDiagonalSum = 0;
  for (let i = 0; i < len; i++) {
    for (let k = 0; k < len; k++) {
      if (i === k) {
        diagonalSum += matrix[i][k];
      }
      if (i + k == len - 1) {
        counterDiagonalSum += matrix[i][k];
      }

    }
  }

  console.log("sum of diagonal elements --- ", diagonalSum)
  console.log("sum of counter diagonal elements ---", counterDiagonalSum)
}
sumOfDiagonals([
  [1, 8, 7],
  [2, 9, 6],
  [3, 4, 5]
]);
Enter fullscreen mode Exit fullscreen mode

The solution above works well but the time and space complexity are O(n^2) time and O(1) where n is the number of elements our loop iterated and power 2 is for the two loops that we used.

Let's try the optimised solution:

function sumOfDiagonals(matrix) {
  const len = matrix.length;
  let diagonalSum = 0;
  let counterDiagonalSum = 0;
  for (let i = 0; i < len; i++) {
    diagonalSum += matrix[i][i];
    counterDiagonalSum += matrix[i][len - i - 1];
  }

  console.log("sum of diagonal elements --- ", diagonalSum)
  console.log("sum of counter diagonal elements ---", counterDiagonalSum)
}
sumOfDiagonals([
  [1, 8, 7],
  [2, 9, 6],
  [3, 4, 5]
]);
Enter fullscreen mode Exit fullscreen mode

Now the time complexity has been reduced to O(n).

Please ❤️ it and share it your with friends or colleagues. Spread the knowledge.


Thats all for now. Keep learning and have faith in Javascript❤️

Top comments (0)