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
- The primary diagonal is
mat[i][i]and the secondary diagonal ismat[i][n - 1 - i]. - Sum both in a single loop over
ifrom0ton - 1. - When
nis odd the centre element lies on both diagonals and has been added twice, so subtract it once. - When
nis 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 - ifor the secondary diagonal: the correct index isn - 1 - i. - Making the correction conditional on the centre value: the correction is structural, independent of the value.