1572. Matrix Diagonal Sum - Explanation
Description
You are 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: 25Example 2:
Input: mat = [
[2,1,3,4],
[1,2,9,8],
[10,11,2,3],
[2,2,2,2]
]
Output: 34Example 3:
Input: mat = [[1]]
Output: 1Constraints:
1 <= mat.length == mat[i].length <= 1001 <= mat[i][j] <= 900
Topics
Prerequisites
Before attempting this problem, you should be comfortable with:
- 2D Array Traversal - Understanding how to access elements in a matrix using row and column indices
- Diagonal Patterns - Recognizing that primary diagonal has i==j and secondary diagonal has i+j==n-1
1. Iteration
Intuition
The matrix has two diagonals: the primary diagonal (top-left to bottom-right) and the secondary diagonal (top-right to bottom-left). We can collect elements from both diagonals by reversing each row after processing the primary diagonal, then processing it again. The center element appears on both diagonals for odd-sized matrices, so we subtract it once to avoid double-counting.
Algorithm
- Define a helper function that iterates through the matrix and sums elements where row index equals column index (primary diagonal), then reverses each row.
- Call the helper twice: first to sum the primary diagonal, then after rows are reversed, to sum what was the secondary diagonal.
- If the matrix dimension
nis odd, subtract the center element (which was counted twice). - Return the total sum.
class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
n = len(mat)
def helper(matrix):
res = 0
for i in range(n):
for j in range(n):
if i == j:
res += matrix[i][j]
matrix[i].reverse()
return res
return helper(mat) + helper(mat) - (mat[n // 2][n // 2] if n & 1 else 0)Time & Space Complexity
- Time complexity:
- Space complexity: extra space.
2. Iteration (Optimal)
Intuition
We can directly compute both diagonal sums in a single pass. For row r, the primary diagonal element is at column r, and the secondary diagonal element is at column n - r - 1. We simply add both for each row. When n is odd, the center element (at row n / 2, column n / 2) is counted twice, so we subtract it once at the end.
Algorithm
- Initialize the result sum to
0. - For each row index
rfrom0ton - 1:- Add
mat[r][r](primary diagonal element). - Add
mat[r][n - r - 1](secondary diagonal element).
- Add
- If
nis odd, subtract the center elementmat[n / 2][n / 2]to correct for double-counting. - Return the result.
Time & Space Complexity
- Time complexity:
- Space complexity: extra space.
Common Pitfalls
Double-Counting the Center Element for Odd-Sized Matrices
When the matrix has an odd dimension, the center element lies on both diagonals and gets added twice. You must subtract it once at the end. Forgetting this check causes incorrect results for odd-sized matrices like 3x3 or 5x5.
Using Incorrect Index Formula for Secondary Diagonal
The secondary diagonal element in row r is at column n - r - 1, not n - r. Using the wrong formula causes an index out of bounds error or accesses the wrong elements.
Sign in to join the discussion