Find Diagonal Sum
Java coding interview problem for Matrix Problems: Find Diagonal Sum.
The Find Diagonal Sum problem is a fundamental matrix problem frequently asked in coding interviews.
It helps developers understand:
- Matrix indexing
- Row-column relationships
- Diagonal traversal
- Boundary conditions
- Optimization techniques
This problem is commonly used as a foundation for advanced matrix problems:
- Diagonal traversal
- Matrix rotation
- Image processing
- Grid-based algorithms
What is Diagonal Sum in Matrix?
A matrix diagonal is a collection of elements that runs diagonally across the matrix.
For a square matrix, there are two important diagonals:
- Primary Diagonal
- Secondary Diagonal
Example Matrix
Consider:
1 2 3
4 5 6
7 8 9
Primary Diagonal
The primary diagonal moves:
Top Left → Bottom Right
Elements:
1
5
9
Sum:
1 + 5 + 9 = 15
Secondary Diagonal
The secondary diagonal moves:
Top Right → Bottom Left
Elements:
3
5
7
Sum:
3 + 5 + 7 = 15
Total Diagonal Sum
Combined:
Primary Diagonal
+
Secondary Diagonal
Result:
15 + 15 = 30
Understanding Matrix Diagonals
For an:
n × n
matrix:
Primary Diagonal Condition
Row index and column index are equal:
i == j
Example:
matrix[0][0]
matrix[1][1]
matrix[2][2]
Secondary Diagonal Condition
Row and column indexes satisfy:
i + j = n - 1
Example:
For:
3 × 3
n:
3
Condition:
i + j = 2
Positions:
[0][2]
[1][1]
[2][0]
Matrix Visualization
Matrix:
Column
0 1 2
Row 0 1 2 3
Row 1 4 5 6
Row 2 7 8 9
Primary diagonal:
(0,0)
(1,1)
(2,2)
Values:
1 5 9
Secondary diagonal:
(0,2)
(1,1)
(2,0)
Values:
3 5 7
Why Is Diagonal Sum Asked in Interviews?
This problem tests:
1. Matrix Index Understanding
Can you correctly map:
row
and
column
?
2. Pattern Recognition
Can you identify:
i == j
and:
i + j = n - 1
?
3. Edge Case Handling
Can you handle:
- Odd matrix size
- Even matrix size
- Duplicate center element
4. Optimization Skills
Can you reduce:
O(n²)
to:
O(n)
?
Real-World Applications
Image Processing
Images are represented as:
Pixel Matrix
Diagonal calculations are used for:
- Image filters
- Pattern detection
- Edge detection
Computer Vision
Diagonal features are used for:
- Shape recognition
- Object detection
Game Development
Grid-based games use diagonal calculations for:
- Movement detection
- Winning conditions
- Board analysis
Data Analysis
Matrices are used for:
- Correlation calculations
- Statistical operations
Problem Statement
Given a square matrix:
n × n
return the sum of:
- Primary diagonal
- Secondary diagonal
If both diagonals contain the same center element, count it only once.
Example 1
Input:
[
[1,2,3],
[4,5,6],
[7,8,9]
]
Output:
25
Explanation:
Primary:
1+5+9 = 15
Secondary:
3+5+7 = 15
Center:
5
appears twice.
Remove duplicate:
15+15-5
Result:
25
Example 2
Input:
[
[1,1,1,1],
[1,1,1,1],
[1,1,1,1],
[1,1,1,1]
]
Primary diagonal:
4
Secondary diagonal:
4
Total:
8
Constraints
Example:
1 <= n <= 100
Matrix:
n × n
Important Observation
For odd-sized matrices:
Example:
3 × 3
The center element belongs to both diagonals.
Example:
1 2 3
4 5 6
7 8 9
Center:
5
appears twice.
For even-sized matrices:
Example:
4 × 4
There is no single center element.
No duplicate handling required.
Approach 1 — Brute Force Traversal
The simplest approach:
- Traverse the complete matrix.
- Check every element.
- Add if it belongs to either diagonal.
Algorithm
For every element:
Check:
Primary diagonal:
i == j
OR
Secondary diagonal:
i + j == n - 1
Add value.
Java Program — Brute Force
public class DiagonalSumBruteForce {
public static int diagonalSum(
int[][] matrix) {
int n =
matrix.length;
int sum = 0;
for(int i = 0;
i < n;
i++) {
for(int j = 0;
j < n;
j++) {
if(i == j ||
i + j == n - 1) {
sum += matrix[i][j];
}
}
}
return sum;
}
public static void main(String[] args) {
int[][] matrix =
{
{1,2,3},
{4,5,6},
{7,8,9}
};
System.out.println(
diagonalSum(matrix));
}
}
Output
25
Step-by-Step Explanation
Input:
1 2 3
4 5 6
7 8 9
Check:
Row 0
Column 0:
i == j
Add:
1
Column 2:
i+j = 2
Add:
3
Row 1
Column 1:
i == j
Add:
5
Also:
i+j = 2
Same element.
Added only once because condition uses:
OR
Row 2
Add:
7
9
Total:
1+3+5+7+9
=
25
Complexity Analysis
We visit every matrix element.
For:
n × n
matrix:
Time:
O(n²)
Space:
O(1)
Advantages
- Easy to understand.
- Simple implementation.
- Handles duplicate center automatically.
Drawbacks
- Checks unnecessary elements.
- Does not use diagonal pattern.
- Slower than optimal solution.
Approach 2 — Single Loop Optimized Approach
Instead of checking every element:
Only visit diagonal positions.
Primary:
matrix[i][i]
Secondary:
matrix[i][n-1-i]
Approach 2 — Single Loop Optimized Approach
The optimized solution uses the mathematical relationship of diagonals.
Instead of checking every element:
n × n
we directly access diagonal elements.
Core Idea
For every row:
Primary diagonal:
matrix[i][i]
Secondary diagonal:
matrix[i][n - 1 - i]
Example
Matrix:
1 2 3
4 5 6
7 8 9
Loop:
i = 0
Primary:
matrix[0][0] = 1
Secondary:
matrix[0][2] = 3
i = 1
Primary:
matrix[1][1] = 5
Secondary:
matrix[1][1] = 5
Same element.
i = 2
Primary:
matrix[2][2] = 9
Secondary:
matrix[2][0] = 7
Without duplicate handling:
1+3+5+5+9+7
=
30
Incorrect.
Avoiding Center Element Double Counting
For odd matrix sizes:
Example:
3 × 3
the center element belongs to both diagonals.
Condition:
i == n - 1 - i
means:
i == n/2
Example:
3 × 3
Center:
matrix[1][1]
should be counted only once.
Java Program — Optimal Approach
public class DiagonalSumOptimal {
public static int diagonalSum(
int[][] matrix) {
int n =
matrix.length;
int sum = 0;
for(int i = 0;
i < n;
i++) {
// Primary diagonal
sum += matrix[i][i];
// Secondary diagonal
if(i != n - 1 - i) {
sum += matrix[i][n - 1 - i];
}
}
return sum;
}
public static void main(String[] args) {
int[][] matrix =
{
{1,2,3},
{4,5,6},
{7,8,9}
};
System.out.println(
diagonalSum(matrix));
}
}
Output
25
Step-by-Step Explanation
Input:
1 2 3
4 5 6
7 8 9
i = 0
Primary:
matrix[0][0]
Value:
1
Secondary:
matrix[0][2]
Value:
3
Sum:
4
i = 1
Primary:
matrix[1][1]
Value:
5
Secondary:
matrix[1][1]
Same position.
Skip duplicate.
Sum:
9
i = 2
Primary:
matrix[2][2]
Value:
9
Secondary:
matrix[2][0]
Value:
7
Final:
1+3+5+9+7
=
25
Complexity Analysis
We visit only:
2 × n
diagonal elements.
Time:
O(n)
Space:
O(1)
Advantages
- Optimal solution.
- Simple implementation.
- No extra memory.
- Interview preferred.
Drawbacks
- Works directly for square matrices.
- Requires understanding index formulas.
Finding Individual Diagonal Sums
Sometimes interviews ask:
Return primary and secondary diagonal sums separately.
Java Program
public class SeparateDiagonalSum {
public static int[] findSums(
int[][] matrix) {
int n =
matrix.length;
int primary = 0;
int secondary = 0;
for(int i = 0;
i < n;
i++) {
primary +=
matrix[i][i];
secondary +=
matrix[i][n - 1 - i];
}
return new int[]{
primary,
secondary
};
}
}
Output Example
Input:
1 2 3
4 5 6
7 8 9
Output:
Primary = 15
Secondary = 15
Rectangular Matrix Diagonal Sum
The diagonal sum problem is usually defined for:
square matrix
because both diagonals have equal length.
Example rectangular matrix:
1 2 3 4
5 6 7 8
9 10 11 12
Primary diagonal:
1
6
11
Sum:
18
Secondary diagonal:
4
7
10
Sum:
21
Rectangular Matrix Java Solution
public class RectangularDiagonalSum {
public static int diagonalSum(
int[][] matrix) {
int rows =
matrix.length;
int cols =
matrix[0].length;
int sum = 0;
int length =
Math.min(rows, cols);
for(int i = 0;
i < length;
i++) {
sum += matrix[i][i];
sum += matrix[i][cols - 1 - i];
}
return sum;
}
}
Complexity Analysis
For:
m × n
matrix:
Time:
O(min(m,n))
Space:
O(1)
Recursive Approach
A recursive solution can also process diagonal elements.
However, recursion is unnecessary here because:
- No branching.
- No repeated computation.
- Simple iteration is better.
Example Recursive Idea
Function:
sum(index)
Process:
matrix[index][index]
and:
matrix[index][n-1-index]
Move:
index + 1
Java Streams Approach
Streams are possible but not recommended.
Example:
int primary =
IntStream.range(0,n)
.map(i -> matrix[i][i])
.sum();
Secondary:
int secondary =
IntStream.range(0,n)
.map(i -> matrix[i][n-1-i])
.sum();
Why Traditional Loops Are Preferred?
Matrix problems require:
- Index control.
- Performance.
- Readability.
Traditional loops are:
- Faster.
- Easier to debug.
- More common in interviews.
Comparison of All Approaches
| Approach | Time Complexity | Space Complexity | Recommendation |
|---|---|---|---|
| Brute Force Traversal | O(n²) | O(1) | Learning |
| Marker Condition Check | O(n²) | O(1) | Better |
| Single Loop Diagonal Access | O(n) | O(1) | Best Solution |
| Streams | O(n) | O(n) | Not Preferred |
Matrix Index Mapping
Primary Diagonal
Formula:
(row,column)
=
(i,i)
Examples:
(0,0)
(1,1)
(2,2)
Secondary Diagonal
Formula:
(i,n-1-i)
Examples for 3×3:
(0,2)
(1,1)
(2,0)
Primitive vs Object Arrays
Primitive Matrix
int[][]
Advantages:
- Faster.
- Less memory.
- Better performance.
Object Matrix
Integer[][]
Advantages:
- Supports null.
- Works with collections.
Disadvantages:
- More memory usage.
Common Interview Mistakes
Mistake 1
Counting center element twice.
Example:
3 × 3 matrix
Mistake 2
Using:
matrix[i][n-i]
Incorrect.
Correct:
matrix[i][n-1-i]
Mistake 3
Assuming only diagonal elements exist when:
i == j
Need both:
Primary
Secondary
Mistake 4
Using nested loops unnecessarily.
Edge Cases
| Input | Result |
|---|---|
| 1×1 Matrix | Single element |
| 2×2 Matrix | Both diagonals |
| 3×3 Matrix | Center handled once |
| All zeros | 0 |
| Negative values | Works |
Interview Follow-up Questions
Q1. Find diagonal sum of matrix.
Q2. Find primary diagonal sum.
Q3. Find secondary diagonal sum.
Q4. Find difference between diagonal sums.
Q5. Print matrix diagonally.
Q6. Find maximum diagonal sum.
Q7. Traverse matrix in zig-zag diagonal order.
Related Problems
- Matrix Transpose
- Matrix Rotation
- Spiral Matrix
- Search in Matrix
- Matrix Multiplication
- Diagonal Traversal
- Toeplitz Matrix
Key Takeaways
Diagonal sum problems are based on simple index patterns.
Primary diagonal:
matrix[i][i]
Secondary diagonal:
matrix[i][n-1-i]
Optimal solution:
One loop
O(n) time
O(1) space
The important interview insight:
Recognize mathematical patterns in matrix indexes instead of scanning the entire matrix.
Frequently Asked Interview Questions
Q1. What is the primary diagonal condition?
row == column
Q2. What is the secondary diagonal condition?
row + column = n - 1
Q3. How do you avoid double counting?
Check:
if(i != n-1-i)
Q4. What is the optimal complexity?
O(n) time
O(1) space
Interview Tip
When asked:
"Find diagonal sum of matrix."
Explain:
- Identify primary diagonal.
- Identify secondary diagonal.
- Use index formulas.
- Handle center element for odd matrices.
For senior interviews, focus on:
- Index mapping.
- Edge cases.
- Space optimization.
This demonstrates strong understanding of matrix traversal patterns.