Matrix Diagonal Sum · Optimal Solution

Two diagonals, one pass, one sum.

An LED display panel uses a square grid of pixels. A quick diagnostic check lights up both diagonals — primary (top-left to bottom-right) and secondary (top-right to bottom-left) — and measures their combined brightness. A single indexed loop walks both diagonals simultaneously, accumulating the sum. When the grid has odd dimensions, the center pixel sits on both diagonals and must be counted only once.


Interactive

Watch the algorithm run


Concept

Two Diagonals, One Overlap

The primary diagonal visits matrix[r][r] — the row and column indices always match. The secondary diagonal visits matrix[r][n − 1 − r] — the column counts down as the row counts up. In an odd-sized matrix both diagonals cross at the center cell matrix[n/2][n/2], which would be double-counted if left uncorrected.


Algorithm

Sum Then Correct

Both diagonals are walked in a single loop. The primary diagonal has col = row; the secondary has col = n − 1 − row.

  1. 1

    Walk the primary diagonal

    For each row r, add matrix[r][r] to the sum.

  2. 2

    Walk the secondary diagonal

    For each row r, add matrix[r][n − 1 − r] to the sum.

  3. 3

    Subtract center if odd

    When n is odd, the center element sits on both diagonals. Subtract it once to correct the double count.


Edge Cases

Edge Patterns

Understanding boundary behavior is as important as the main algorithm path.

Even-sized matrix

When n is even, no cell sits on both diagonals. The sum is simply the sum of both diagonals — no correction needed.

1 × 1 matrix

A single cell is both diagonals and the center. The answer is that single value.


Complexity

Complexity

Time: O(n) — one pass over the rows.
Space: O(1) — only a running sum.