Compute the sum of the primary and secondary diagonals of a square matrix, counting the center element only once.
Matrix Diagonal Sum
Given an square matrix of integers, return the sum of all values on the primary diagonal and secondary diagonal.
- The primary diagonal contains cells where row index equals column index.
- The secondary diagonal contains cells where row index plus column index equals .
If the matrix has an odd size, the center cell belongs to both diagonals, so count it only once.
Input Format
- A square matrix
matof sizen x n.
Output Format
- Return a single integer: the diagonal sum.
Constraints
- The matrix is square:
n == mat.length == mat[i].length - Values may be positive, negative, or zero.
Hints
- Traverse one row at a time and add the two diagonal positions for that row.
- Be careful not to double count the middle element when
nis odd.
Input Format
mat: ann x ninteger matrix
Output Format
- Integer sum of both diagonals with the center counted once
Constraints
- Square matrix only
- Count overlapping center cell once
- Integer values may be negative or zero
Example 1
Input
mat = [[1,2,3],[4,5,6],[7,8,9]]
Output
25
Explanation
Primary diagonal = 1 + 5 + 9 = 15. Secondary diagonal = 3 + 5 + 7 = 15. The center 5 is counted once, so total = 15 + 15 - 5 = 25.
Example 2
Input
mat = [[5]]
Output
5
Explanation
There is only one cell, which lies on both diagonals. Count it once.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.