Magicsheet logo

Matrix Diagonal Sum

Easy
12.5%
Updated 8/1/2025

Matrix Diagonal Sum

What is this problem about?

The Matrix Diagonal Sum problem asks you to calculate the sum of the elements on the primary and secondary diagonals of a square n x n matrix. The primary diagonal runs from the top-left to the bottom-right. The secondary diagonal runs from the top-right to the bottom-left. Crucially, if the matrix has an odd size, the center element belongs to both diagonals, but it should only be added to the sum once.

Why is this asked in interviews?

This is a classic warm-up or screening problem. It is designed to test basic 2D array indexing and whether a candidate can avoid writing nested loops for a problem that only requires a single pass. It evaluates your attention to detail regarding the overlapping center element in odd-sized matrices.

Algorithmic pattern used

This relies on a simple Single Pass / Math Iteration pattern. You do not need to traverse the entire N×NN \times N grid. You only need to iterate i from 0 to n - 1.

  • The primary diagonal element at row i is always matrix[i][i].
  • The secondary diagonal element at row i is always matrix[i][n - 1 - i]. Add both to your running total. After the loop, if n is odd, subtract the exact center element matrix[n/2][n/2] from your total because it was added twice.

Example explanation

Matrix:

1 2 3
4 5 6
7 8 9

Size n = 3.

  • i = 0: Add mat[0][0] (1) and mat[0][2] (3). Total = 4.
  • i = 1: Add mat[1][1] (5) and mat[1][1] (5). Total = 4 + 10 = 14.
  • i = 2: Add mat[2][2] (9) and mat[2][0] (7). Total = 14 + 16 = 30. Since n is odd (3), the center element mat[1][1] (5) was added twice. We subtract it once: 30 - 5 = 25. Final answer is 25.

Common mistakes candidates make

The most glaring mistake is writing a double for loop to traverse the entire matrix, checking if (row == col || row + col == n - 1). While this gets the correct answer and handles the center overlap automatically, it takes O(N2)O(N^2) time. The optimal solution is O(N)O(N). Interviewers will immediately dock points for using a double loop when a single loop suffices.

Interview preparation tip

When working with square matrices, memorize the coordinates for diagonals. Primary diagonal: (i, i). Secondary diagonal: (i, n - 1 - i). If you immediately write a single loop using these coordinates, you signal to the interviewer that you are highly comfortable with 2D array geometry and index manipulation.

Similar Questions