easy Problem 2 Matrix Diagonal Sum
Problem Statement
Given a square matrix (2D array), calculate the sum of its two diagonals.
The two diagonals in consideration are the primary diagonal that spans from the top-left to the bottom-right and the secondary diagonal that spans from top-right to bottom-left. If a number is part of both diagonals (which occurs only for odd-sized matrices), it should be counted only once in the sum.
Examples
- Example 1:
- Input:
[[1,2,3], [4,5,6], [7,8,9]] - Expected Output: 25
- Justification: Summing up the two diagonals (1+5+9+3+7), we get 25. Please note that the element at [1][1] = 5 is counted only once.
- Input:
- Example 2:
- Input:
[[1,0], [0,1]] - Expected Output: 2
- Justification: The sum of the two diagonals is 1+1 = 2.
- Input:
- Example 3:
- Input:
[[5]] - Expected Output: 5
- Justification: Since there's only one element, it is the sum itself.
- Input:
Constraints:
n == mat.length == mat[i].length1 <= n <= 1001 <= mat[i][j] <= 100
Try it yourself
Try solving this question here:
✅ Solution Matrix Diagonal Sum
Problem Statement
Given a square matrix (2D array), calculate the sum of its two diagonals.
The two diagonals in consideration are the primary diagonal that spans from the top-left to the bottom-right and the secondary diagonal that spans from top-right to bottom-left. If a number is part of both diagonals (which occurs only for odd-sized matrices), it should be counted only once in the sum.
Examples
- Example 1:
- Input:
[[1,2,3], [4,5,6], [7,8,9]] - Expected Output: 25
- Justification: Summing up the two diagonals (1+5+9+3+7), we get 25. Please note that the element at [1][1] = 5 is counted only once.
- Input:
- Example 2:
- Input:
[[1,0], [0,1]] - Expected Output: 2
- Justification: The sum of the two diagonals is 1+1 = 2.
- Input:
- Example 3:
- Input:
[[5]] - Expected Output: 5
- Justification: Since there's only one element, it is the sum itself.
- Input:
Constraints:
n == mat.length == mat[i].length1 <= n <= 1001 <= mat[i][j] <= 100
Solution
The primary algorithmic approach for this problem is straightforward yet efficient, involving a single loop traversal through the matrix, accumulating the sum of the diagonal elements as it progresses. This approach is effective in that it avoids unnecessary calculations or traversals through the matrix, adhering strictly to the diagonal indices to retrieve the values to be summed. The main mechanism involves identifying and summing the elements of the primary and secondary diagonal, ensuring that, if the matrix size is odd, the central element (which belongs to both diagonals) is not double-counted.
Step-by-Step Agorithm
-
Initialize Sum: Start by initializing a variable to store the sum of the diagonal elements. Let's call this variable
diagonalSum. -
Loop Through Matrix: Iterate through the matrix using a loop. Since the matrix is square, you can use a single index to traverse both rows and columns. Let's use
ias the loop variable, ranging from 0 to the length of the matrix minus one. -
Add Primary Diagonal Elements: In each iteration, add the element at the primary diagonal to
diagonalSum. The primary diagonal elements are those where the row and column indices are equal, i.e.,matrix[i][i]. -
Add Secondary Diagonal Elements: In the same iteration, add the element at the secondary diagonal to
diagonalSum. The secondary diagonal elements are those where the column index is the complement of the row index, i.e.,matrix[i][matrix.length - 1 - i]. -
Avoid Double Counting: If the matrix has an odd number of rows and columns, the central element will be counted twice (once for each diagonal). To correct this, subtract the central element from
diagonalSum. The central element is at the positionmatrix[middle][middle], wheremiddle = matrix.length / 2. -
Return the Result: After completing the loop, return the value of
diagonalSum. This is the sum of the elements on both diagonals of the matrix.
Algorithm Walkthrough
- Initialize
totalSumto 0. - Loop
ifrom 0 ton-1(inclusive). Wherenis the size of the matrix (3 in this example).- Add
mat[i][i]andmat[i][n-i-1]tototalSum. - For
i=0, add 1+3 tototalSum=>totalSum= 4. - For
i=1, add 5+5 tototalSum=>totalSum= 14. - For
i=2, add 9+7 tototalSum=>totalSum= 30.
- Add
- Since
nis odd, subtract the central elementmat[n/2][n/2](which is 5) fromtotalSumto correct for double-counting =>totalSum= 25. - Return
totalSumwhich is 25.
Code
Here is the code for this algorithm:
public class Solution {
public int diagonalSum(int[][] mat) {
int n = mat.length; // Get the size of the matrix
int totalSum = 0; // Initialize the total sum
// Loop through each row
for (int i = 0; i < n; i++) {
totalSum += mat[i][i] + mat[i][n - i - 1]; // Add primary and secondary diagonal elements
}
// If n is odd, subtract the central element
if (n % 2 != 0) {
totalSum -= mat[n / 2][n / 2];
}
return totalSum; // Return the calculated total sum
}
// Main method to test the examples
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(
sol.diagonalSum(new int[][] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } })
); // Output: 25
System.out.println(sol.diagonalSum(new int[][] { { 1, 0 }, { 0, 1 } })); // Output: 2
System.out.println(sol.diagonalSum(new int[][] { { 5 } })); // Output: 5
}
}
Complexity Analysis
Time Complexity
-
Single loop over rows: The algorithm iterates over the matrix once, accessing the elements on both the primary and secondary diagonals. Since the matrix is
n x n, the loop runstimes, where nis the number of rows (or columns) in the matrix. -
Additional operations: For each row, two elements are accessed and added (one from the primary diagonal and one from the secondary diagonal), which are constant time operations,
. -
Therefore, the total time complexity is
.
Overall time complexity:
Space Complexity
- Constant space: The algorithm uses only a few extra variables (
n,totalSum), which require constant space. No additional data structures are used that depend on the input size.
Overall space complexity:
🤖 Don't fully get this? Learn it with Claude
Stuck on Problem 2 Matrix Diagonal Sum? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Problem 2 Matrix Diagonal Sum** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Problem 2 Matrix Diagonal Sum** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Problem 2 Matrix Diagonal Sum**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Problem 2 Matrix Diagonal Sum**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.