Matrix Diagonal Sum - Problem
Matrix Diagonal Sum is a fundamental matrix manipulation problem that tests your understanding of 2D array indexing. Given a square matrix mat, you need to calculate the sum of elements on both diagonals.

The primary diagonal runs from top-left to bottom-right (elements where i == j), while the secondary diagonal runs from top-right to bottom-left (elements where i + j == n - 1). The key challenge is avoiding double-counting the center element in odd-sized matrices, where both diagonals intersect.

Goal: Return the sum of all diagonal elements, counting the center element only once.
Input: A square matrix mat of size n ร— n
Output: An integer representing the sum of diagonal elements

Input & Output

example_1.py โ€” 3x3 Matrix
$ Input: mat = [[1,2,3],[4,5,6],[7,8,9]]
โ€บ Output: 25
๐Ÿ’ก Note: Primary diagonal: 1 + 5 + 9 = 15. Secondary diagonal: 3 + 5 + 7 = 15. Center element 5 is counted twice, so total = 15 + 15 - 5 = 25.
example_2.py โ€” 4x4 Matrix
$ Input: mat = [[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,1,1]]
โ€บ Output: 8
๐Ÿ’ก Note: Primary diagonal: 1 + 1 + 1 + 1 = 4. Secondary diagonal: 1 + 1 + 1 + 1 = 4. No center overlap in even-sized matrix, so total = 4 + 4 = 8.
example_3.py โ€” 1x1 Matrix
$ Input: mat = [[5]]
โ€บ Output: 5
๐Ÿ’ก Note: Single element matrix - the only element is both on primary and secondary diagonal, but counted once. Result = 5.

Constraints

  • n == mat.length == mat[i].length
  • 1 โ‰ค n โ‰ค 100
  • 1 โ‰ค mat[i][j] โ‰ค 100
  • The matrix is always square

Visualization

Tap to expand
Matrix Diagonal Sum Visualization1234567Algorithm Steps1. Initialize sum = 02. For i = 0 to n-1:โ€ข Add mat[i][i] to sumโ€ข Add mat[i][n-1-i] to sum3. If n is odd: subtract center onceExample CalculationPrimary diagonal: 1 + 5 + 7 = 13Secondary diagonal: 4 + 5 + 6 = 15Center overlap: -5Total: 13 + 15 - 5 = 23
Understanding the Visualization
1
Identify Diagonals
Primary diagonal (โ†˜): i==j positions. Secondary diagonal (โ†™): i+j==n-1 positions
2
Single Pass
For each row, access both mat[i][i] and mat[i][n-1-i] simultaneously
3
Handle Overlap
In odd-sized matrices, center element appears on both diagonals - subtract once
4
Return Sum
Total sum represents all diagonal elements counted exactly once
Key Takeaway
๐ŸŽฏ Key Insight: The optimal solution recognizes that we only need to visit diagonal elements, and cleverly handles the center overlap by subtracting it once when the matrix size is odd.
Asked in
Amazon 25 Google 18 Microsoft 15 Meta 12
45.2K Views
Medium Frequency
~8 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen