Skip to main content
Back to problems
Leetcode
Easy
Arrays
Matrices
Math
Matrix Diagonal Sum

Compute the sum of the primary and secondary diagonals of a square matrix, counting the center element only once.

Acceptance 0%
Problem Statement

Matrix Diagonal Sum

Given an n×nn \times n square matrix of integers, return the sum of all values on the primary diagonal and secondary diagonal.

  • The primary diagonal contains cells where row index equals column index.
  • The secondary diagonal contains cells where row index plus column index equals n1n - 1.

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

Input Format

  • A square matrix mat of size n x n.

Output Format

  • Return a single integer: the diagonal sum.

Constraints

  • The matrix is square: n == mat.length == mat[i].length
  • 1n1 \le n
  • Values may be positive, negative, or zero.

Hints

  • Traverse one row at a time and add the two diagonal positions for that row.
  • Be careful not to double count the middle element when n is odd.

Input Format

  • mat: an n x n integer matrix

Output Format

  • Integer sum of both diagonals with the center counted once

Constraints

  • Square matrix only
  • Count overlapping center cell once
  • Integer values may be negative or zero
Examples
Sample cases returned by the problem API.

Example 1

Input

mat = [[1,2,3],[4,5,6],[7,8,9]]

Output

25

Explanation

Primary diagonal = 1 + 5 + 9 = 15. Secondary diagonal = 3 + 5 + 7 = 15. The center 5 is counted once, so total = 15 + 15 - 5 = 25.

Example 2

Input

mat = [[5]]

Output

5

Explanation

There is only one cell, which lies on both diagonals. Count it once.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.