Matrix Diagonal Sum
Problem
Given an n x n square matrix mat, return the sum of the matrix diagonals (primary and secondary; count center once if overlapping).
mat = [[1,2,3],[4,5,6],[7,8,9]]25def diagonal_sum(mat):
n = len(mat); total = 0
for i in range(n):
total += mat[i][i] + mat[i][n-1-i]
if n & 1: total -= mat[n // 2][n // 2]
return total
function diagonalSum(mat) {
const n = mat.length; let total = 0;
for (let i = 0; i < n; i++) total += mat[i][i] + mat[i][n-1-i];
if (n & 1) total -= mat[n >> 1][n >> 1];
return total;
}
class Solution {
public int diagonalSum(int[][] mat) {
int n = mat.length, total = 0;
for (int i = 0; i < n; i++) total += mat[i][i] + mat[i][n-1-i];
if ((n & 1) == 1) total -= mat[n/2][n/2];
return total;
}
}
int diagonalSum(vector>& mat) {
int n = mat.size(), total = 0;
for (int i = 0; i < n; i++) total += mat[i][i] + mat[i][n-1-i];
if (n & 1) total -= mat[n/2][n/2];
return total;
}
Explanation
We need the sum of both diagonals of a square matrix, but counting the very center twice when the size is odd would be wrong. The clean approach grabs both diagonal cells per row and then fixes the overlap once at the end.
For each row i, the primary diagonal cell is mat[i][i] and the secondary diagonal cell is mat[i][n-1-i]. We add both for every row.
When n is odd, the two diagonals cross at the middle cell mat[n/2][n/2], which we just added twice. So we subtract it once with the check if n & 1.
That single subtraction is all the special-casing we need; for even n the diagonals never touch, so nothing is subtracted.
Example: [[1,2,3],[4,5,6],[7,8,9]]. Primary 1+5+9=15, secondary 3+5+7=15, total 30, minus the center 5 = 25.