Matrix Diagonal Sum

Given a square matrix mat, return the sum of the matrix diagonals.

Only include:

  • All elements on the primary diagonal.
  • All elements on the secondary diagonal that are not part of the primary diagonal.
Example 1
1 2 3
4 5 6
7 8 9
Inputmat = [[1,2,3],[4,5,6],[7,8,9]]
Output25
Diagonals sum to 1 + 5 + 9 + 3 + 7 = 25, with mat[1][1] = 5 counted only once.
Example 2
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
Inputmat = [[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,1,1]]
Output8
The primary and secondary diagonals contain eight distinct elements, each equal to 1, so the sum is 8.

Constraints

  • n == mat.length == mat[i].length
  • 1 <= n <= 100
  • 1 <= mat[i][j] <= 100

Asked at 6 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate