49. Matrix Diagonal Sum

EasyArrayArray

Given a square matrix mat, return the sum of the matrix diagonals — the primary diagonal (top-left to bottom-right) plus the secondary diagonal (top-right to bottom-left). If an element is at the intersection (center of odd-sized matrix), count it only once.

Input: A square 2D integer array mat of size n x n.

Output: Integer — sum of both diagonals without double-counting the center.

Examples

Example 1
Input: [[1,2,3],[4,5,6],[7,8,9]]
Output: 25
Explanation: Primary: 1+5+9=15. Secondary: 3+5+7=15. Center 5 counted twice → 15+15-5=25.
Example 2
Input: [[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,1,1]]
Output: 8
Explanation: Primary:4, Secondary:4. No center overlap (even n). Total=8.
Example 3
Input: [[5]]
Output: 5
Explanation: 1x1: only element is both diagonals. Return 5.

Constraints

Asked by

AmazonMicrosoftGoogleMeta
Solve this problem in the editor →