Matrix Diagonal Sum

Easy~10 min

Given an n x n square matrix matrix, return the sum of the elements on both diagonals.

The primary diagonal runs from top-left to bottom-right. The secondary diagonal runs from top-right to bottom-left.

If the matrix has an odd size, the center element belongs to both diagonals — count it only once.

Examples

Example 1
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: 25
Explanation: Primary diagonal: 1 + 5 + 9 = 15. Secondary diagonal: 3 + 5 + 7 = 15. Center element 5 is shared, so total = 15 + 15 - 5 = 25.
Example 2
Input: matrix = [[1,2],[3,4]]
Output: 10
Explanation: Primary diagonal: 1 + 4 = 5. Secondary diagonal: 2 + 3 = 5. No overlap. Total = 10.
Example 3
Input: matrix = [[5]]
Output: 5
Explanation: Only one element, which is on both diagonals. Count it once.

Constraints

  • n == matrix.length == matrix[i].length
  • 1 <= n <= 100
  • -1000 <= matrix[i][j] <= 1000
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run