Problem

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.

Examples

Example 1:

Input: mat = [[1 ,2, 3],
			  [4, 5 ,6],
			  [7, 8, 9]]
Output: 25
Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25
Notice 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

Solution

Method 1 - Iteration

You are tasked with finding the sum of a square matrix’s diagonals:

  • Primary diagonal: Elements are on mat[i][i] for 0 ≤ i < n.
  • Secondary diagonal: Elements are on mat[i][n - i - 1] for 0 ≤ i < n.
  • Avoid counting overlapping elements in the primary and secondary diagonals twice.

Key Insight

  • The matrix is square (n x n), so the primary and secondary diagonals both share the same row/column range [0, n).
  • If i equals n - i - 1 (like in the middle of the matrix for odd n), the element belongs to both diagonals. We account for this by summing it once.

Approach

  1. Initialise a variable ans to store the sum.
  2. Traverse each row of the matrix mat using an index i from 0 to n-1.
  3. Add the element mat[i][i] (primary diagonal) to ans.
  4. Add the element mat[i][n - i - 1] (secondary diagonal) to ans only if i is not n - i - 1, to prevent double-counting.
  5. Return ans.

Code

Java
class Solution {
    public int diagonalSum(int[][] mat) {
        int n = mat.length;
        int ans = 0;
        for (int i = 0; i < n; i++) {
            ans += mat[i][i]; // Add primary diagonal
            if (i != n - i - 1) { // Add secondary diagonal if not overlapping
                ans += mat[i][n - i - 1];
            }
        }
        return ans;
    }
}
Python
class Solution:
    def diagonalSum(self, mat: List[List[int]]) -> int:
        n = len(mat)
        ans = 0
        for i in range(n):
            ans += mat[i][i]  # Add primary diagonal
            if i != n - i - 1:  # Add secondary diagonal if not overlapping
                ans += mat[i][n - i - 1]
        return ans

Complexity

  • ⏰ Time complexity: O(n) since we iterate over n rows once.
  • 🧺 Space complexity: O(1) since we only use a few variables for computation.