Matrix Diagonal Sum

EasyMatrixsimulation

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given a square n x n integer matrix mat, return the sum of the entries on its primary diagonal (top-left to bottom-right) and its secondary diagonal (top-right to bottom-left). When n is odd the two diagonals cross at the center cell; count that cell **only once**. Solve it in O(n) time.

Examples

Input: mat = [[1,2,3],[4,5,6],[7,8,9]]
Output: 25
1 + 5 + 9 + 3 + 7 = 25; the shared 5 is counted once.
Input: mat = [[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,1,1]]
Output: 8
With even n the diagonals share no cell, giving 4 + 4.
Input: mat = [[5]]
Output: 5
The single cell is on both diagonals but counted once.

Constraints

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

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More simulation problems