You are given a square matrix mat of size n x n.
Your task:
Return the sum of the matrix’s primary diagonal and secondary diagonal.
Example:
Input: [[1,2,3], [4,5,6], [7,8,9]] Output: 25 Explanation: Primary diagonal: 1 + 5 + 9 = 15 Secondary diagonal: 3 + 5 + 7 = 15 Total = 30 but center element counted twice → subtract 5 Final = 25
Another example:
Input: [[5]] Output: 5
Problem Understanding
Important details:
- Matrix is always square (same number of rows and columns)
- Two diagonals:
- Primary diagonal at positions (i, i)
- Secondary diagonal at positions (i, n-1-i)
- If n is odd, the center element belongs to both diagonals and must be counted only once
- Must return integer sum
Key insight:
For each row i, add:
mat[i][i] primary diagonal mat[i][n - 1 - i] secondary diagonal
And avoid double-count when i == n – 1 – i.
Logic Explained in Simple English
The simplest way to solve it:
- Loop through all rows (i from 0 to n-1)
- Add the primary diagonal element at (i, i)
- Add the secondary diagonal element at (i, n-1-i)
- If both indices point to the same cell:
- subtract one copy (or avoid adding twice)
Why this works:
- Each diagonal element appears exactly once
- Only center element in odd-sized matrix overlaps
- No need to loop through entire matrix
This produces optimal and clean code.
Step-by-Step Approach
- Let n = mat.length
- Initialize sum = 0
- For i from 0 to n-1:
- sum += mat[i][i]
- sum += mat[i][n – 1 – i]
- If n is odd:
- subtract center element once
center index is (n/2, n/2)
- subtract center element once
- Return sum
Java Implementation
class Solution {
public int diagonalSum(int[][] mat) {
int n = mat.length;
int sum = 0;
for (int i = 0; i < n; i++) {
sum += mat[i][i]; // primary diagonal
sum += mat[i][n - 1 - i]; // secondary diagonal
}
if (n % 2 == 1) {
int center = mat[n / 2][n / 2];
sum -= center; // remove double-count
}
return sum;
}
}
Dry Run Example
Input:
[ [1,2,3], [4,5,6], [7,8,9] ]
n = 3
sum = 0
Iteration:
i=0:
primary = mat[0][0] = 1
secondary = mat[0][2] = 3
sum = 4
i=1:
primary = mat[1][1] = 5
secondary = mat[1][1] = 5
sum = 14
i=2:
primary = mat[2][2] = 9
secondary = mat[2][0] = 7
sum = 30
n is odd → subtract center:
center = mat[1][1] = 5
sum = 30 – 5 = 25
Output:
25
Time and Space Complexity
Time Complexity
O(n)
Only one loop through rows.
Space Complexity
O(1)
No extra data structures used.
Common Mistakes and How to Avoid Them
Mistake 1: Double-counting the center element
Happens when n is odd.
Fix by subtracting once (or conditionally adding).
Mistake 2: Looping through entire matrix
Unnecessary — diagonals accessed directly.
Mistake 3: Miscalculating secondary diagonal index
Correct formula:
(n - 1 - i)
Mistake 4: Assuming primary and secondary diagonals never overlap
They overlap when:
i == n - 1 - i → middle of odd matrix
Mistake 5: Using nested loops
Adds needless complexity and runtime.
