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.
Examples
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].length
1 <= n <= 100
1 <= mat[i][j] <= 100
Solution
Method 1 - Iteration
You are tasked with finding the sum of a square matrix’s diagonals:
- Primary diagonal: Elements are on
mat[i][i]
for0 ≤ i < n
. - Secondary diagonal: Elements are on
mat[i][n - i - 1]
for0 ≤ i < n
. - Avoid counting overlapping elements in the primary and secondary diagonals twice.
Key Insight
- The matrix is square (
n x n
), so the primary and secondary diagonals both share the same row/column range [0, n). - If
i
equalsn - i - 1
(like in the middle of the matrix for oddn
), the element belongs to both diagonals. We account for this by summing it once.
Approach
- Initialise a variable
ans
to store the sum. - Traverse each row of the matrix
mat
using an indexi
from0
ton-1
. - Add the element
mat[i][i]
(primary diagonal) toans
. - Add the element
mat[i][n - i - 1]
(secondary diagonal) toans
only ifi
is notn - i - 1
, to prevent double-counting. - Return
ans
.
Code
Java
class Solution {
public int diagonalSum(int[][] mat) {
int n = mat.length;
int ans = 0;
for (int i = 0; i < n; i++) {
ans += mat[i][i]; // Add primary diagonal
if (i != n - i - 1) { // Add secondary diagonal if not overlapping
ans += mat[i][n - i - 1];
}
}
return ans;
}
}
Python
class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
n = len(mat)
ans = 0
for i in range(n):
ans += mat[i][i] # Add primary diagonal
if i != n - i - 1: # Add secondary diagonal if not overlapping
ans += mat[i][n - i - 1]
return ans
Complexity
- ⏰ Time complexity:
O(n)
since we iterate overn
rows once. - 🧺 Space complexity:
O(1)
since we only use a few variables for computation.