Matrix Diagonal Sum — LeetCode 1572 Python Solution

EasyArrayMatrix
Problem
#1572
Reading time
2 min

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

Python
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 ans

Complexity

MeasureComplexity
TimeO(n), where n is the number of rows in the matrix
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview