1572. Matrix Diagonal Sum - Explanation

Problem Link

Description

You are 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: 25

Example 2:

Input: mat = [
    [2,1,3,4],
    [1,2,9,8],
    [10,11,2,3],
    [2,2,2,2]
]

Output: 34

Example 3:

Input: mat = [[1]]

Output: 1

Constraints:

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


Company Tags

Please upgrade to NeetCode Pro to view company tags.



Prerequisites

Before attempting this problem, you should be comfortable with:

  • 2D Array Traversal - Understanding how to access elements in a matrix using row and column indices
  • Diagonal Patterns - Recognizing that primary diagonal has i==j and secondary diagonal has i+j==n-1

1. Iteration

Intuition

The matrix has two diagonals: the primary diagonal (top-left to bottom-right) and the secondary diagonal (top-right to bottom-left). We can collect elements from both diagonals by reversing each row after processing the primary diagonal, then processing it again. The center element appears on both diagonals for odd-sized matrices, so we subtract it once to avoid double-counting.

Algorithm

  1. Define a helper function that iterates through the matrix and sums elements where row index equals column index (primary diagonal), then reverses each row.
  2. Call the helper twice: first to sum the primary diagonal, then after rows are reversed, to sum what was the secondary diagonal.
  3. If the matrix dimension n is odd, subtract the center element (which was counted twice).
  4. Return the total sum.
class Solution:
    def diagonalSum(self, mat: List[List[int]]) -> int:
        n = len(mat)

        def helper(matrix):
            res = 0
            for i in range(n):
                for j in range(n):
                    if i == j:
                        res += matrix[i][j]
                matrix[i].reverse()
            return res

        return helper(mat) + helper(mat) - (mat[n // 2][n // 2] if n & 1 else 0)

Time & Space Complexity

  • Time complexity: O(n2)O(n ^ 2)
  • Space complexity: O(1)O(1) extra space.

2. Iteration (Optimal)

Intuition

We can directly compute both diagonal sums in a single pass. For row r, the primary diagonal element is at column r, and the secondary diagonal element is at column n - r - 1. We simply add both for each row. When n is odd, the center element (at row n / 2, column n / 2) is counted twice, so we subtract it once at the end.

Algorithm

  1. Initialize the result sum to 0.
  2. For each row index r from 0 to n - 1:
    • Add mat[r][r] (primary diagonal element).
    • Add mat[r][n - r - 1] (secondary diagonal element).
  3. If n is odd, subtract the center element mat[n / 2][n / 2] to correct for double-counting.
  4. Return the result.
class Solution:
    def diagonalSum(self, mat: List[List[int]]) -> int:
        res, n = 0, len(mat)

        for r in range(n):
            res += mat[r][r]
            res += mat[r][n - r - 1]

        return res - (mat[n // 2][n // 2] if n & 1 else 0)

Time & Space Complexity

  • Time complexity: O(n)O(n)
  • Space complexity: O(1)O(1) extra space.

Common Pitfalls

Double-Counting the Center Element for Odd-Sized Matrices

When the matrix has an odd dimension, the center element lies on both diagonals and gets added twice. You must subtract it once at the end. Forgetting this check causes incorrect results for odd-sized matrices like 3x3 or 5x5.

Using Incorrect Index Formula for Secondary Diagonal

The secondary diagonal element in row r is at column n - r - 1, not n - r. Using the wrong formula causes an index out of bounds error or accesses the wrong elements.