Sum of Both Diagonals of a Square Matrix

Solve this Problem
Easy10–15 min
Topics
Companies
Practice:GFG ↗
Given a square matrix mat of size n × n, return the sum of the elements on both diagonals — the primary diagonal (top-left to bottom-right) and the secondary diagonal (top-right to bottom-left). If the matrix has an odd number of rows and columns, the very center cell sits on both diagonals at once — count it only once. Checking every cell is correct but wasteful: the diagonal positions are known in advance by a simple formula, so a single pass that visits only those 2n (or 2n-1) cells finds the answer in O(n) instead of O(n²).

Test Case 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 shared center (5) is only counted once, so 15+15-5=25.

Test Case 2:

Input:mat = [[5]]
Output:5
Explanation:A single cell sits on both diagonals at once — it's still just counted once.

Test Case 3:

Input:mat = [[1,2],[3,4]]
Output:10
Explanation:An even-sized matrix has no shared center: primary 1+4=5, secondary 2+3=5, total 10.

Constraints

  • 1 ≤ n ≤ 100
  • 1 ≤ mat[i][j] ≤ 100
  • mat is a square matrix (n × n)
🚀

Try the Dry Run

Don't just read the solution — watch it execute, one step at a time.

🧪Try your own test case
1class Solution {
2 public int diagonalSum(int[][] mat) {
3 int n = mat.length;
4 int sum = 0;
5 for (int i = 0; i < n; i++) {
6 sum += mat[i][i];
7 if (i != n - 1 - i) sum += mat[i][n - 1 - i];
8 }
9 return sum;
10 }
11}
12
1
2
3
4
5
6
7
8
9
Variables
n3
sum0
INITIALIZE

Start sum at 0. Walk i from 0 to 2, adding mat[i][i] and mat[i][n-1-i] at each step — no need to scan the whole matrix.

Step 1 / 8

Approach & Solutions

Brute Force

Brute

Check every cell of the matrix, and add it to the running sum if it sits on either diagonal — the primary diagonal (i === j) or the secondary diagonal (i + j === n - 1). Correct, but visiting every cell revisits n² - 2n+1 cells that were never going to be added.

TimeO(n²)
SpaceO(1)
1class Solution { 2 public int diagonalSum(int[][] mat) { 3 int n = mat.length; 4 int sum = 0; 5 for (int i = 0; i < n; i++) { 6 for (int j = 0; j < n; j++) { 7 if (i == j || i + j == n - 1) sum += mat[i][j]; 8 } 9 } 10 return sum; 11 } 12}

Optimal — Single Pass

Optimal

There's no need to check every cell — the diagonal positions are already known by formula. Walk i from 0 to n-1 once, adding mat[i][i] (primary) and mat[i][n-1-i] (secondary) at each step, skipping the secondary add when i equals n-1-i to avoid double-counting the shared center of an odd-sized matrix.

TimeO(n)
SpaceO(1)
1class Solution { 2 public int diagonalSum(int[][] mat) { 3 int n = mat.length; 4 int sum = 0; 5 for (int i = 0; i < n; i++) { 6 sum += mat[i][i]; 7 if (i != n - 1 - i) sum += mat[i][n - 1 - i]; 8 } 9 return sum; 10 } 11}

Related Problems