Matrix Diagonal Sum Problem
#1572
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1572.
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.
Example 1:

Input: mat = [[1,2,3],
[4,5,6],
[7,8,9]]
Output: 25
Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25
Notice that element mat[1][1] = 5 is counted only once.
Example 2:
Input: mat = [[1,1,1,1],
[1,1,1,1],
[1,1,1,1],
[1,1,1,1]]
Output: 8
Example 3:
Input: mat = [[5]]
Output: 5
Constraints:
n == mat.length == mat[i].length1 <= n <= 1001 <= mat[i][j] <= 100
Solution
Approach: One Pass Over the Rows
Each row i has exactly one cell on the primary diagonal, mat[i][i], and one on the secondary diagonal, mat[i][n - 1 - i]. Add both for every row.
The only catch is the center: when n is odd, the middle row has i == n - 1 - i, so both diagonals meet in the same cell. Add it once there, not twice.
Complexity: O(n) time, since we touch two cells per row, and O(1) extra space.
class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
n = len(mat)
total = 0
for i, row in enumerate(mat):
j = n - 1 - i # column of the secondary diagonal in this row
total += row[i] + (row[j] if j != i else 0) # the center cell counts once
return total