Skip to main content

Matrix Diagonal Sum

Problem statement

Given a square matrix mat, return the sum of the matrix diagonals.

Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.

Example 1:

Input: mat = [[1,2,3],              [4,5,6],              [7,8,9]]Output: 25Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25Notice that element mat[1][1] = 5 is counted only once.

Example 2:

Input: mat = [[1,1,1,1],              [1,1,1,1],              [1,1,1,1],              [1,1,1,1]]Output: 8

Example 3:

Input: mat = [[5]]Output: 5

Constraints:

  • n == mat.length == mat[i].length
  • 1 <= n <= 100
  • 1 <= mat[i][j] <= 100

My solution

/**
* @param {number[][]} mat
* @return {number}
*/
var diagonalSum = function(mat) {
let left = [0, 0];
let right = [0, mat.length - 1];

let sum = 0;
let i = 0;
while (i < mat.length) {
// console.log("slot", mat[left[0], left[1]])

sum += mat[left[0]][left[1]] + (left.join("") === right.join("") ? 0 : mat[right[0]][right[1]])

left = [left[0] + 1, left[1] + 1];
right = [right[0] + 1, right[1] - 1];

// console.log(left);

i++;
}

return sum
};


/*

0, 0
1, 1
2, 2
3, 3


0, 2
1, 1
2, 0


0, 0
1, 1
2, 2
3, 3

1, 3
1, 2
2, 1
3, 0

*/