Introduction
Finding the sum of the diagonal elements is a common matrix problem in Java and frequently appears in coding interviews. A square matrix contains two diagonals:
- Main diagonal (Primary diagonal) – from the top-left corner to the bottom-right corner.
- Anti-diagonal (Secondary diagonal) – from the top-right corner to the bottom-left corner.
Calculating the main diagonal sum is straightforward. However, when summing both diagonals, there's an important edge case: the center element of an odd-sized matrix belongs to both diagonals. If you're not careful, it gets counted twice.
In this tutorial, you'll learn how to calculate the main diagonal sum, the sum of both diagonals, and how to correctly avoid double-counting the center element.
Problem Statement
Given the following matrix:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Main diagonal:
1 + 5 + 9 = 15
Anti-diagonal:
3 + 5 + 7 = 15
Notice that the center element (5) belongs to both diagonals.
Method 1: Sum of the Main Diagonal
The main diagonal contains elements where the row index equals the column index.
Formula:
matrix[i][i]
Java Program
public class Main {
public static void main(String[] args) {
int[][] matrix = {
{1,2,3},
{4,5,6},
{7,8,9}
};
int sum = 0;
for (int i = 0; i < matrix.length; i++) {
sum += matrix[i][i];
}
System.out.println("Main Diagonal Sum = " + sum);
}
}
Output
Main Diagonal Sum = 15
Time Complexity
O(n)
Space Complexity
O(1)
Method 2: Sum of Both Diagonals (Double-Counting Bug)
A simple approach is to add both diagonal elements during each iteration.
Java Program
public class Main {
public static void main(String[] args) {
int[][] matrix = {
{1,2,3},
{4,5,6},
{7,8,9}
};
int n = matrix.length;
int total = 0;
for (int i = 0; i < n; i++) {
total += matrix[i][i];
total += matrix[i][n - 1 - i];
}
System.out.println(total);
}
}
Output
30
Although the program runs correctly, the result is not the sum of distinct diagonal elements.
The center element (5) has been counted twice:
Main Diagonal
1 + 5 + 9 = 15
Anti Diagonal
3 + 5 + 7 = 15
Total
15 + 15 = 30
Method 3: Sum of Both Diagonals Without Double Counting
To avoid counting the center element twice, check whether the main and anti-diagonal positions are different.
Java Program
public class Main {
public static void main(String[] args) {
int[][] matrix = {
{1,2,3},
{4,5,6},
{7,8,9}
};
int n = matrix.length;
int total = 0;
for (int i = 0; i < n; i++) {
total += matrix[i][i];
if (i != n - 1 - i) {
total += matrix[i][n - 1 - i];
}
}
System.out.println(total);
}
}
Output
25
Now the center element (5) is counted only once.
Time Complexity
O(n)
Space Complexity
O(1)
Step-by-Step Explanation
Consider this code:
for (int i = 0; i < n; i++) {
total += matrix[i][i];
if (i != n - 1 - i) {
total += matrix[i][n - 1 - i];
}
}
Here's what happens:
- Add the current main diagonal element.
- Determine the anti-diagonal element.
- Check whether both indexes refer to the same cell.
- If they are different, add the anti-diagonal element.
- Otherwise, skip it to avoid double counting.
Internal Working
For the following matrix:
{
{1,2,3},
{4,5,6},
{7,8,9}
}
Iteration 1
Main = 1
Anti = 3
Total = 4
Iteration 2
Main = 5
Anti = 5
Same position
Total = 9
The anti-diagonal value is skipped because it is the same element.
Iteration 3
Main = 9
Anti = 7
Total = 25
Final answer:
25
Distinct diagonal elements are:
1
3
5
7
9
Real-Life Analogy
Imagine two roads crossing in the middle of a city.
If you're counting all the buildings along both roads, the building at the intersection belongs to both roads.
To count unique buildings, you should include the intersection building only once.
The center element of an odd-sized matrix behaves exactly like that intersection.
Best Practices
- Use
matrix[i][i]for the main diagonal. - Use
matrix[i][n - 1 - i]for the anti-diagonal. - Decide whether the problem requires counting the center element once or twice.
- Use
i != n - 1 - iwhen calculating the sum of distinct diagonal elements. - Test your solution using both odd-sized and even-sized matrices.
- Ensure the matrix is square before applying diagonal formulas.
Common Mistakes
Counting the Center Element Twice
Incorrect:
total += matrix[i][i];
total += matrix[i][n - 1 - i];
Correct:
total += matrix[i][i];
if (i != n - 1 - i) {
total += matrix[i][n - 1 - i];
}
Testing Only Even-Sized Matrices
The bug does not appear for even-sized matrices because they have no single center element.
Always test with a 3 × 3 or 5 × 5 matrix.
Confusing Different Problem Statements
Some questions ask for:
Main Diagonal Sum
+
Anti Diagonal Sum
Others ask for:
Sum of distinct diagonal elements
These are not the same calculation.
Applying the Logic to Rectangular Matrices
Diagonal formulas are intended for square matrices.
Always validate:
matrix.length == matrix[0].length
Expert Tips
- The condition
i != n - 1 - i
is a popular interview question because it demonstrates awareness of edge cases.
- Even-sized matrices never have overlapping diagonal elements, so the condition is always true.
- If you're unsure what a coding problem expects, read the statement carefully to determine whether duplicate counting is intended.
- Diagonal sum problems are commonly followed by questions involving identity matrices, diagonal traversal, and matrix rotations.
Comparison of Approaches
| Approach | Odd-Sized Matrix Result | Counts Center Twice? | Best Use Case |
|---|---|---|---|
| Main diagonal only | Main diagonal sum | No | Main diagonal problems |
| Both diagonals (without check) | Includes duplicate center | Yes | When duplicate counting is intentional |
Both diagonals (i != n - 1 - i) |
Distinct diagonal sum | No | Most coding interview problems |
Frequently Asked Questions
Why does the sum become larger than expected?
Because the center element of an odd-sized matrix belongs to both diagonals and is added twice.
How do I avoid double counting?
Use:
if (i != n - 1 - i)
before adding the anti-diagonal element.
Does this problem occur for even-sized matrices?
No. Even-sized matrices have no single center element shared by both diagonals.
Is counting the center twice always wrong?
No. It depends on the problem statement. Some problems intentionally require adding both diagonal sums separately.
What is the main diagonal sum of the example matrix?
15
What is the sum of distinct diagonal elements?
25
How can I verify my solution?
Test it with a 3 × 3 matrix and manually calculate the expected answer.
Where are diagonal sums used?
Diagonal sums are used in matrix algorithms, linear algebra, identity matrix validation, scientific computing, image processing, and coding interview questions.