Matrix Diagonal Sum

Given a square matrix `mat`, return the sum of its two diagonals: every cell on the primary diagonal (top-left to bottom-right) plus every cell on the secondary diagonal (top-right to bottom-left) that is not already on the primary one.

30:00

Matrix Diagonal Sum
easy
Free written solution
Topics
Companies

Given a square matrix mat, return the sum of its two diagonals: every cell on the primary diagonal (top-left to bottom-right) plus every cell on the secondary diagonal (top-right to bottom-left) that is not already on the primary one.

Example 1:
Input: {"mat":[[1,2,3],[4,5,6],[7,8,9]]}
Output: 25
Constraints:
  • n==mat.length==mat[i].lengthn == \text{mat.length} == \text{mat}[i].\text{length}

  • 1≤n≤1001 \leq n \leq 100

  • 1≤mat[i][j]≤1001 \leq \text{mat}[i][j] \leq 100

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"mat":[[1,2,3],[4,5,6],[7,8,9]]}

total starts at 0. Row i touches the primary diagonal at column i and the secondary diagonal at column 3-1-i.

primary mat[i][i]

secondary mat[i][n-1-i]

1
2
3
4
5
6
7
8
9

running total

=

0

Variables
VariableValue
total0
DepthFunction Call
Stack empty
0/7