matrix
diagonals
sum calculation
linear algebra
mathematics

calculate the sum of diagonals in a matrix

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Diagonal sums show up in programming interviews, matrix algorithms, board-game logic, and image processing. The task sounds simple, but a correct solution depends on whether you need the main diagonal, the secondary diagonal, or both without counting the center twice.

Identify the Two Diagonals

For a square matrix, the main diagonal runs from the top-left cell to the bottom-right cell. In zero-based indexing, those values live at matrix[i][i].

The secondary diagonal runs from the top-right cell to the bottom-left cell. Its column index moves in the opposite direction, so the values live at matrix[i][n - 1 - i], where n is the number of rows.

Given this matrix:

text
1 2 3
4 5 6
7 8 9

The main diagonal is 1, 5, 9, and the secondary diagonal is 3, 5, 7.

That center value matters. In an odd-sized matrix, the middle element belongs to both diagonals. Some problems want it counted twice because it appears on both diagonals. Other problems want the total of all diagonal cells only once. You need to decide which interpretation the problem expects before writing code.

Sum Each Diagonal in One Pass

The most direct solution is to loop once over the rows and compute both sums at the same time. This keeps the code easy to read and runs in linear time relative to the matrix size.

python
1def diagonal_sums(matrix):
2    n = len(matrix)
3
4    if any(len(row) != n for row in matrix):
5        raise ValueError("matrix must be square")
6
7    main_sum = 0
8    secondary_sum = 0
9
10    for i in range(n):
11        main_sum += matrix[i][i]
12        secondary_sum += matrix[i][n - 1 - i]
13
14    return main_sum, secondary_sum
15
16
17matrix = [
18    [1, 2, 3],
19    [4, 5, 6],
20    [7, 8, 9],
21]
22
23print(diagonal_sums(matrix))  # (15, 15)

This approach uses O(n) time and O(1) extra space. That is optimal for a dense in-memory matrix because you must inspect each diagonal element at least once.

Compute a Combined Diagonal Total

Some interview problems ask for the sum of both diagonals together. If the matrix has odd size, the center element appears in both diagonals, so a naive sum will count it twice.

Here is a version that returns the total of all diagonal cells exactly once:

python
1def distinct_diagonal_total(matrix):
2    n = len(matrix)
3
4    if any(len(row) != n for row in matrix):
5        raise ValueError("matrix must be square")
6
7    total = 0
8
9    for i in range(n):
10        total += matrix[i][i]
11        if i != n - 1 - i:
12            total += matrix[i][n - 1 - i]
13
14    return total
15
16
17matrix = [
18    [1, 2, 3],
19    [4, 5, 6],
20    [7, 8, 9],
21]
22
23print(distinct_diagonal_total(matrix))  # 25

The result is 25 because the diagonal cells are 1, 3, 5, 7, 9, and the center value 5 is counted once.

If a problem statement says “sum of both diagonals” without more detail, check its example output. That usually reveals whether duplicate counting is expected.

A Compact NumPy Version

If you are working in scientific Python, NumPy gives you a concise way to extract diagonal values. This is useful in notebooks and data-heavy code, although the loop version is often clearer in interviews.

python
1import numpy as np
2
3matrix = np.array([
4    [1, 2, 3, 4],
5    [5, 6, 7, 8],
6    [9, 10, 11, 12],
7    [13, 14, 15, 16],
8])
9
10main_sum = np.trace(matrix)
11secondary_sum = np.fliplr(matrix).trace()
12
13print(main_sum)       # 34
14print(secondary_sum)  # 34

np.trace sums the main diagonal. To get the secondary diagonal, np.fliplr flips the matrix left to right, turning the secondary diagonal into a main diagonal.

This version is expressive, but it assumes you already use NumPy. For standalone algorithm practice, plain Python is usually the better choice.

When the Matrix Is Not Square

Diagonal questions usually assume an n x n matrix. If the input is rectangular, the idea of a full secondary diagonal becomes ambiguous because the number of rows and columns differs.

You have two reasonable options:

  1. Reject the input and require a square matrix.
  2. Define custom behavior, such as using min(rows, cols) elements.

For knowledge-base content and interview-style questions, rejecting non-square input is usually the cleanest answer because it matches the standard mathematical definition.

Common Pitfalls

The most common bug is double-counting the center cell in an odd-sized matrix when the problem expects distinct diagonal cells. Guard against that with a condition like if i != n - 1 - i.

Another mistake is assuming the matrix is square without checking. If one row is shorter than expected, matrix[i][n - 1 - i] can fail or silently produce the wrong result in loosely validated code.

Indexing errors are also common. The secondary diagonal uses n - 1 - i, not n - i. Missing that - 1 shifts every lookup and can produce an out-of-range error.

Finally, avoid overcomplicating the solution. You do not need nested loops to sum diagonals. One loop is enough because every row contributes at most two relevant cells.

Summary

  • The main diagonal uses matrix[i][i].
  • The secondary diagonal uses matrix[i][n - 1 - i].
  • A single loop is enough to compute both sums in O(n) time.
  • For odd-sized matrices, decide whether the center cell should be counted once or twice.
  • Validate that the matrix is square before relying on diagonal indexing.

Course illustration
Course illustration

All Rights Reserved.