NeetCode #885LC-1572EasyMath & Geometry
← Back to All Problems

#885 · #1572 · Matrix Diagonal Sum(矩阵对角线元素的和)

📌 Problem Statement & Constraints

Given a square matrix mat, return the sum of the elements on the primary diagonal (top-left to bottom-right) and the secondary diagonal (top-right to bottom-left). If an element belongs to both diagonals, it is counted only once. Constraints: 1 <= n <= 100, 1 <= mat[i][j] <= 100.

💡 Core Algorithmic Approaches

  1. The primary diagonal is mat[i][i] and the secondary diagonal is mat[i][n - 1 - i].
  2. Sum both in a single loop over i from 0 to n - 1.
  3. When n is odd the centre element lies on both diagonals and has been added twice, so subtract it once.
  4. When n is even the diagonals are disjoint and no correction is needed.

💻 Benchmark Python3 Implementation

class Solution:
    def diagonalSum(self, mat: List[List[int]]) -> int:
        n = len(mat)
        total = 0
        for i in range(n):
            total += mat[i][i]            # primary diagonal
            total += mat[i][n - 1 - i]    # secondary diagonal
        if n % 2:
            total -= mat[n // 2][n // 2]  # centre counted twice
        return total

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): one pass over the diagonal length.
💾 Space Complexity
O(1).

⚠️ Interview Pitfalls & Follow-ups

  • Forgetting the centre correction for odd n: the centre is counted twice, over-counting by its value.
  • Applying the correction for even n: there is no shared element, so the correction would under-count.
  • Using index n - i for the secondary diagonal: the correct index is n - 1 - i.
  • Making the correction conditional on the centre value: the correction is structural, independent of the value.