Matrix Diagonal Sum - Problem

Given a square matrix mat, return the sum of the matrix diagonals.

Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.

The primary diagonal consists of elements where row index = column index. The secondary diagonal consists of elements where row index + column index = n - 1, where n is the matrix size.

Input & Output

Example 1 — 3×3 Matrix
$ Input: mat = [[1,2,3],[4,5,6],[7,8,9]]
Output: 25
💡 Note: Primary diagonal: mat[0][0] + mat[1][1] + mat[2][2] = 1 + 5 + 9 = 15. Secondary diagonal: mat[0][2] + mat[2][0] = 3 + 7 = 10. The center element 5 is shared, so total = 15 + 10 = 25.
Example 2 — 2×2 Matrix
$ Input: mat = [[1,1],[1,1]]
Output: 4
💡 Note: Primary diagonal: mat[0][0] + mat[1][1] = 1 + 1 = 2. Secondary diagonal: mat[0][1] + mat[1][0] = 1 + 1 = 2. No overlap in even-sized matrix, so total = 2 + 2 = 4.
Example 3 — 1×1 Matrix
$ Input: mat = [[5]]
Output: 5
💡 Note: Only one element which is both primary and secondary diagonal. Count it once: 5.

Constraints

  • n == mat.length == mat[i].length
  • 1 ≤ n ≤ 100
  • 1 ≤ mat[i][j] ≤ 100

Visualization

Tap to expand
Matrix Diagonal Sum Problem Overview123456789Input MatrixPrimary Diagonal: 1 + 5 + 9 = 15Secondary Diagonal: 3 + 7 = 10Center Element: 5 (counted once)Total Sum15 + 10 = 25🎯 Key Insight: Sum both diagonals but count center element only once
Understanding the Visualization
1
Input Matrix
3×3 square matrix with primary and secondary diagonals highlighted
2
Sum Diagonals
Add elements from both diagonals, handling center overlap
3
Final Sum
Return total sum avoiding double-count
Key Takeaway
🎯 Key Insight: The main trick is to access diagonal elements directly in O(n) time while properly handling the center element overlap in odd-sized matrices
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 6
24.1K Views
Medium Frequency
~8 min Avg. Time
892 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