#1572
Easy Algorithms Matrix diagonal sum
Array Matrix
84.2% acceptance
Feb 25, 2026
3791
69
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.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn diagonal_sum(mat: Vec<Vec<i32>>) -> i32 {
let n = mat.len();
let mut sum = 0;
for i in 0..n {
sum += mat[i][i]; // primary diagonal
sum += mat[i][n - 1 - i]; // secondary diagonal
}
// If n is odd, center element was counted twice
if n % 2 == 1 {
sum -= mat[n / 2][n / 2];
}
sum
}
}