Problem
Given a square matrix of integers, return the sum of all elements that lie on the primary diagonal (top-left to bottom-right) or the secondary diagonal (top-right to bottom-left). If the matrix has an odd number of rows, the center element sits on both diagonals โ count it only once.
- Input:
mat = [[1,2,3],[4,5,6],[7,8,9]] - Output:
25 - Explanation: Primary diagonal gives 1, 5, 9; secondary gives 3, 5, 7; center 5 appears in both, so 1+3+5+9+7 = 25.
Counter-example showing the overlap: for a 3ร3 matrix the center is at mat[1][1]. Both diagonals pass through it, so a naive double-count yields 30 โ subtracting 5 once gives the correct 25.
Intuition
Each row contributes exactly one element to the primary diagonal and one to the secondary. Walking rows once is all that's needed. The only wrinkle is that when n is odd the center element lands in both sets โ a single conditional subtraction after the loop handles it cleanly.
Solution โ Single Pass
Walk through every row, adding both diagonal elements, then correct for the double-counted center if n is odd.
- Get the matrix size
n. - Initialize
total = 0. - For each row index
i, addmat[i][i](primary) andmat[i][n-1-i](secondary) tototal. - If
nis odd, subtractmat[n//2][n//2]โ the center was added in step 3 as both diagonals' contribution. - Return
total.
1def diagonalSum(mat: list[list[int]]) -> int:
2 n = len(mat)
3 total = 0
4 for i in range(n):
5 total += mat[i][i] # primary diagonal element for this row
6 total += mat[i][n - 1 - i] # secondary diagonal element for this row
7 if n % 2 == 1:
8 total -= mat[n // 2][n // 2] # center was included in both diagonals above
9 return totalTime: O(n) โ one pass through n rows, each doing constant work.
Space: O(1) โ only a running total is kept.
Complexity Summary
| Approach | Time | Space | When to use |
|---|---|---|---|
| Single Pass | O(n) | O(1) | Always โ the diagonal structure guarantees one element per row |
Common Mistakes
- Forgetting the center subtraction for odd n โ when n is odd,
mat[n//2][n//2]satisfies bothrow == colandrow + col == n-1, so the loop adds it twice; skip the check and the answer is off by that value. - Using
n - iinstead ofn - 1 - ifor the secondary diagonal column โ the secondary element in rowiis at columnn - 1 - i(zero-indexed), notn - i, which would be out of bounds on the last row. - Reaching for a nested O(nยฒ) loop โ iterating every cell and checking
if row == col or row + col == n - 1works but is unnecessary; the single-row loop is both simpler and faster. - Checking
n % 2 == 0to decide whether to subtract the center โ only odd-sized matrices have a center that straddles both diagonals, so the condition should ben % 2 == 1.
Related Problems
spiral-matrixโ traversing a 2D matrix by manipulating row and column indices explicitlyrotate-imageโ in-place matrix transformation that relies on the same diagonal index arithmeticset-matrix-zeroesโ modifying matrix elements based on which row/column they occupyreshape-the-matrixโ mapping 2D matrix positions to a flat index and backsearch-a-2d-matrixโ treating matrix coordinates as first-class values for efficient access