Sum of Both Diagonals of a Square Matrix
Solve this Problemmat 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:
Test Case 2:
Test Case 3:
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.
| 1 | class 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 |
30Start 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.
Approach & Solutions
Brute Force
BruteCheck 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.
O(n²)O(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
OptimalThere'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.
O(n)O(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}