Matrix Diagonal Sum — LeetCode 1572 Python Solution
- Problem
- #1572
- Pattern
- Matrix and Grid
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- mat = [[1,2,3],
- Output
- 25
- Explanation
- Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25
Python solution
class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
ans = 0
n = len(mat)
for i, row in enumerate(mat):
j = n - i - 1
ans += row[i] + (0 if j == i else row[j])
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the number of rows in the matrix |
| Space | O(1) auxiliary |
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 1572. Matrix Diagonal Sum is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Matrix.
The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1572. Matrix Diagonal Sum?
- LeetCode 1572. Matrix Diagonal Sum is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1572. Matrix Diagonal Sum?
- The Python solution on this page runs in O(n), where n is the number of rows in the matrix.
- What is the space complexity of LeetCode 1572. Matrix Diagonal Sum?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1572. Matrix Diagonal Sum cover?
- LeetCode 1572. Matrix Diagonal Sum is tagged Array and Matrix on LeetCode.