Matrix Diagonals
Hard · 75 XPFor the 3×3 matrix in the starter, print the sum of the main diagonal, then the sum of the anti-diagonal.
22 18
Main: matrix[i][i]. Anti: matrix[i][len(matrix)-1-i].
matrix = [
[5, 1, 3],
[2, 8, 4],
[7, 6, 9],
]
n = len(matrix)
print(sum(matrix[i][i] for i in range(n)))
print(sum(matrix[i][n - 1 - i] for i in range(n)))
Run your code to check it…
How to approach Matrix Diagonals
A matrix in Python is a list of rows, so matrix[row][col] reaches any cell. The main diagonal is every cell where the row and column are the same: matrix[i][i].
The anti-diagonal runs from top-right to bottom-left. As the row goes up from 0, the column comes down from the last index, so the cell is matrix[i][n - 1 - i] for an n × n matrix. Sum each with a generator over range(n).
Worked through on this data
- Main diagonal: matrix[0][0] = 5, matrix[1][1] = 8, matrix[2][2] = 9. 5 + 8 + 9 = 22.
- Anti-diagonal: matrix[0][2] = 3, matrix[1][1] = 8, matrix[2][0] = 7. 3 + 8 + 7 = 18.
- Two prints give 22 and 18. In an odd-sized matrix both diagonals share the centre cell, here the 8.
Common mistakes
- Writing
matrix[i][n - i]: on the first row that is index 3, past the end, and raises an IndexError. - Hard-coding 3 instead of
len(matrix), so the code breaks on any other size. - Adding both diagonals into one total and counting the centre cell twice when the task asks for a combined sum.
Time and space
Each diagonal visits n cells: O(n) time and O(1) extra space, even though the matrix holds n² values.
Where this shows up
Grid indexing shows up in image processing, game boards (checking a tic-tac-toe win is this exact problem) and the trace of a matrix in linear algebra.
Take it further
Write has_winner(board) for a 3 × 3 tic-tac-toe board that checks every row, column and both diagonals.