Leetcode 1572. Matrix Diagonal Sum
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.
1 2 3
4 5 6
7 8 9
The sum should be: 1 + 5 + 9 (primary diagonal) + 3 + 7 (secondary diagonal, excluding the center element 5) = 1 + 5 + 9 + 3 + 7 = 25.
i
within the range, add mat[i][i]
(primary diagonal element) to the sum.mat[i][n-i-1]
(secondary diagonal element) to the sum.i == n-i-1
), subtract that element from the sum once to avoid double-counting.public class Solution {
public int diagonalSum(int[][] mat) {
int n = mat.length;
int sum = 0;
for (int i = 0; i < n; i++) {
// Add the primary diagonal element
sum += mat[i][i];
// Add the secondary diagonal element
sum += mat[i][n - i - 1];
}
// If the matrix has an odd dimension, subtract the center element once if it was added twice
if (n % 2 == 1) {
sum -= mat[n / 2][n / 2];
}
return sum;
}
}
O(n)
, where n
is the number of rows/columns in the matrix. We are iterating over the matrix only once.O(1)
, as we are using a constant amount of extra space regardless of the input size.Feel free to ask any further questions or for additional clarifications!
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?