1572. Matrix Diagonal Sum
Description
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: 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
Solutions
Solution 1: Row-by-Row Traversal
We can traverse each row $\textit{row}[i]$ of the matrix. For each row, we calculate the elements on the two diagonals, i.e., $\textit{row}[i][i]$ and $\textit{row}[i][n - i - 1]$, where $n$ is the number of rows in the matrix. If $i = n - i - 1$, it means there is only one element on the diagonals of the current row; otherwise, there are two elements. We add these elements to the answer.
After traversing all rows, we get the answer.
The time complexity is $O(n)$, where $n$ is the number of rows in the matrix. The space complexity is $O(1)$.
Python3
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
Java
class Solution {
public int diagonalSum(int[][] mat) {
int ans = 0;
int n = mat.length;
for (int i = 0; i < n; ++i) {
int j = n - i - 1;
ans += mat[i][i] + (i == j ? 0 : mat[i][j]);
}
return ans;
}
}
C++
class Solution {
public:
int diagonalSum(vector<vector<int>>& mat) {
int ans = 0;
int n = mat.size();
for (int i = 0; i < n; ++i) {
int j = n - i - 1;
ans += mat[i][i] + (i == j ? 0 : mat[i][j]);
}
return ans;
}
};
Go
func diagonalSum(mat [][]int) (ans int) {
n := len(mat)
for i, row := range mat {
ans += row[i]
if j := n - i - 1; j != i {
ans += row[j]
}
}
return
}
TypeScript
function diagonalSum(mat: number[][]): number {
let ans = 0;
const n = mat.length;
for (let i = 0; i < n; ++i) {
const j = n - i - 1;
ans += mat[i][i] + (i === j ? 0 : mat[i][j]);
}
return ans;
}
Rust
impl Solution {
pub fn diagonal_sum(mat: Vec<Vec<i32>>) -> i32 {
let n = mat.len();
let mut ans = 0;
for i in 0..n {
ans += mat[i][i];
let j = n - i - 1;
if j != i {
ans += mat[i][j];
}
}
ans
}
}
C
int diagonalSum(int** mat, int matSize, int* matColSize) {
int ans = 0;
for (int i = 0; i < matSize; ++i) {
ans += mat[i][i];
int j = matSize - i - 1;
if (j != i) {
ans += mat[i][j];
}
}
return ans;
}