Sum of Both Diagonals of a Square Matrix
Implement diagonalSum
Given a square matrix
mat of size n × n, return the sum of the elements on both diagonals — the primary diagonal (top-left to bottom-right) and the secondary diagonal (top-right to bottom-left). If the matrix has an odd number of rows and columns, the very center cell sits on both diagonals at once — count it only once.
Checking every cell is correct but wasteful: the diagonal positions are known in advance by a simple formula, so a single pass that visits only those 2n (or 2n-1) cells finds the answer in O(n) instead of O(n²).
Example 1:
Input: mat = [[1,2,3],[4,5,6],[7,8,9]]
Output: 25
Example 2:
Input: mat = [[5]]
Output: 5
Example 3:
Input: mat = [[1,2],[3,4]]
Output: 10
+ 7 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ n ≤ 100 - ●
1 ≤ mat[i][j] ≤ 100 - ●
mat is a square matrix (n × n)
mat =
[[1,2,3], [4,5,6], [7,8,9]]