Skip to content
← All posts

Matrix Diagonal Sum: Primary and Secondary Diagonals

5 min read
leetcodeproblemeasymatrix

Given a square matrix mat, return the sum of the elements on both diagonals. If an element sits on both diagonals (the center of an odd-sized matrix), count it only once.

This is LeetCode 1572: Matrix Diagonal Sum, and it is a clean introduction to working with matrix indices. The solution boils down to one loop and one small adjustment.

123456789
Blue = primary diagonal (mat[i][i]), green = secondary diagonal (mat[i][n-1-i]), amber = center element counted in both.

Why this problem matters

Matrix diagonal sum teaches you the relationship between row index and column index for diagonal elements. For the primary diagonal, the column equals the row: mat[i][i]. For the secondary diagonal, the column is the mirror image: mat[i][n - 1 - i]. Once that index relationship clicks, you can apply it to problems involving diagonal traversals, anti-diagonal groupings, and any situation where you need to identify which diagonal a cell belongs to.

The problem is simple, but the pattern behind it is everywhere. Valid Sudoku checks 3x3 boxes using similar index arithmetic. N-Queens uses diagonal membership to prune search. Diagonal traversal problems in general rely on these exact formulas.

The key insight

You do not need to visit every cell in the matrix. You only care about cells on one of the two diagonals. There are at most 2n - 1 such cells (two diagonals of length n, minus one shared center if n is odd).

For each row i from 0 to n - 1:

  • The primary diagonal element is at column i, so add mat[i][i].
  • The secondary diagonal element is at column n - 1 - i, so add mat[i][n - 1 - i].

If n is odd, the center element at mat[n // 2][n // 2] gets added twice (once as part of each diagonal). Subtract it once to correct the double-count.

That is the entire algorithm: one pass through the rows, then a single conditional subtraction.

The solution

def diagonalSum(mat: list[list[int]]) -> int:
    n = len(mat)
    total = 0

    for i in range(n):
        total += mat[i][i]
        total += mat[i][n - 1 - i]

    if n % 2 == 1:
        total -= mat[n // 2][n // 2]

    return total

The loop runs n times. In each iteration, you add two elements: the primary diagonal cell and the secondary diagonal cell. When i equals n - 1 - i (which only happens at i = n // 2 when n is odd), both additions target the same cell. The if n % 2 == 1 block removes the extra copy.

You could alternatively check inside the loop whether i != n - 1 - i before adding the secondary diagonal, avoiding the post-loop subtraction. Both approaches work, but the version above is slightly cleaner because it keeps the loop body uniform and handles the edge case in one place.

When n is even, the two diagonals never share a cell, so the subtraction never fires. You only need to worry about double-counting the center when n is odd. A quick way to remember: odd-sized matrices have a single center cell, even-sized ones do not.

Visual walkthrough

Let's trace through the algorithm with a 3x3 matrix. Watch how each row contributes two diagonal elements, and how the center gets corrected at the end.

Step 1: i = 0. Add mat[0][0] and mat[0][2].

123456789

total += 1 + 3 = 4. Primary picks top-left, secondary picks top-right.

Step 2: i = 1. Add mat[1][1] and mat[1][1].

123456789

total += 5 + 5 = 14. Both diagonals land on the center cell.

Step 3: i = 2. Add mat[2][2] and mat[2][0].

123456789

total += 9 + 7 = 30. Primary picks bottom-right, secondary picks bottom-left.

Step 4: n is odd, so subtract the center element mat[1][1].

123456789

total -= 5 = 25. The center was double-counted, so we remove one copy.

The final answer is 25. The primary diagonal contributes 1 + 5 + 9 = 15. The secondary diagonal contributes 3 + 5 + 7 = 15. Together that is 30, but the center element 5 was counted twice, so we subtract it once to get 25.

Complexity analysis

MetricValue
TimeO(n)
SpaceO(1)

Time: the loop iterates n times, doing constant work per iteration. The conditional check at the end is O(1).

Space: no extra data structures. Just a running total and the loop variable.

Building blocks

This problem is built on two reusable patterns that show up across many matrix problems.

1. Diagonal traversal

The formula mat[i][i] for the primary diagonal and mat[i][n - 1 - i] for the secondary diagonal. Any time a problem asks about diagonals of a square matrix, these are the index expressions you reach for. You will see them in N-Queens (checking diagonal attacks), diagonal printing, and anti-diagonal grouping.

2. Index math for matrix patterns

The broader skill of translating a geometric pattern (like "the secondary diagonal") into an index formula (like column = n - 1 - row). This same thinking applies to rotating a matrix (mat[j][n - 1 - i]), transposing (mat[j][i]), and reflecting (mat[i][n - 1 - j]). Once you are comfortable converting visual patterns into index expressions, matrix problems become much more approachable.

Edge cases

  • 1x1 matrix: [[5]] returns 5. The single element is on both diagonals, but the odd-size correction subtracts it once, giving 5 + 5 - 5 = 5.
  • 2x2 matrix: [[1, 2], [3, 4]] returns 1 + 4 + 2 + 3 = 10. No center element to subtract since n is even.
  • All zeroes: returns 0. The algorithm works regardless of values.
  • Large values: the sum can grow large, but Python handles arbitrary-precision integers natively.

From understanding to recall

You have read through the solution and understand the index formulas. The next step is making sure you can reproduce them from scratch when a diagonal-related problem comes up in an interview.

The formulas themselves are simple: mat[i][i] and mat[i][n - 1 - i]. But under pressure, it is easy to second-guess whether the secondary diagonal formula uses n - 1 - i or n - i, or to forget the odd-size center correction. These are the kinds of small details that spaced repetition locks in.

CodeBricks drills the diagonal traversal pattern and the index-math building block separately. You practice writing the formulas from memory at increasing intervals until they are automatic. When a matrix diagonal problem appears, you do not need to re-derive anything. You just write it.

Related posts

  • Spiral Matrix - Another matrix traversal pattern where index management is the core challenge
  • Set Matrix Zeroes - In-place matrix manipulation using row and column markers
  • Valid Sudoku - Uses box-index math similar to diagonal-index math for checking 3x3 subgrids