Compute the sum of the primary and secondary diagonals of a square matrix, counting the center element only once.
Given an square matrix of integers, return the sum of all values on the primary diagonal and secondary diagonal.
If the matrix has an odd size, the center cell belongs to both diagonals, so count it only once.
mat of size n x n.n == mat.length == mat[i].lengthn is odd.mat: an n x n integer matrixExample 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
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.