1677. Matrix Diagonal Sum
My accepted Python solution to LeetCode problem 1677, Matrix Diagonal Sum, running in 0ms.
- Difficulty: Easy
- Python
- Runtime 0ms
- Memory 17.9MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 0ms, memory 17.9MB, accepted 2025-12-29.
class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
# Sum primary diagonal (i,i) and secondary diagonal (i, n-1-i)
# If n is odd, center is counted twice, so subtract once
# Time: O(n), Space: O(1)
n = len(mat)
total = 0
for i in range(n):
total += mat[i][i] # Primary diagonal
total += mat[i][n - 1 - i] # Secondary diagonal
# If n is odd, center was counted twice
if n % 2 == 1:
total -= mat[n // 2][n // 2]
return total