sagelearnai

Matrix Diagonal Sum

Difficulty: Easy · Pattern: Matrix · LeetCode #1572

Return the sum of the primary diagonal and the secondary diagonal of a square matrix, counting the center element only once.

Examples

text
[[1,2,3],[4,5,6],[7,8,9]]  →  25    (1+5+9 + 3+7)
[[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,1,1]]  →  8

Hints

  1. Row i contributes mat[i][i] and mat[i][n−1−i]. These are the same cell only when n is odd and i is the middle row.

Approach

Make one pass: add both diagonal cells of each row, and if n is odd, subtract mat[n//2][n//2] once. O(n) instead of O(n²).

Complexity

Time: O(n). Space: O(1).

Python solution
def diagonalSum(mat):
    n = len(mat)
    total = sum(mat[i][i] + mat[i][n - 1 - i] for i in range(n))
    return total - (mat[n // 2][n // 2] if n % 2 else 0)
JavaScript solution
function diagonalSum(mat) {
  const n = mat.length;
  let total = 0;
  for (let i = 0; i < n; i++) total += mat[i][i] + mat[i][n - 1 - i];
  return n % 2 ? total - mat[n >> 1][n >> 1] : total;
}