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 INPUT 3x3 Square Matrix 1 2 3 4 5 6 7 8 9 Primary Diagonal Secondary Diagonal Center (Both) mat = [[1,2,3],[4,5,6],[7,8,9]] ALGORITHM STEPS 1 Initialize sum = 0, n = 3 2 Loop i = 0 to n-1 Traverse each row once 3 Add Primary Diag sum += mat[i][i] 4 Add Secondary Diag sum += mat[i][n-1-i] (if i != n-1-i) Calculation: i=0: sum += 1 + 3 = 4 i=1: sum += 5 (center) (skip dup: 5 counted once) i=2: sum += 9 + 7 = 16 Total: 4 + 5 + 16 = 25 FINAL RESULT 1 3 5 7 9 Selected elements: 1 + 3 + 5 + 7 + 9 OUTPUT 25 OK - Diagonal Sum Complete Key Insight: Single pass O(n) traversal: For each row i, add mat[i][i] (primary) and mat[i][n-1-i] (secondary). When n is odd, the center element (where i == n-1-i) is on BOTH diagonals -- count it only once! TutorialsPoint - Matrix Diagonal Sum | Single Pass Diagonal Traversal
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