LeetCode 1572: Matrix Diagonal Sum Solution
Master LeetCode problem 1572 (Matrix Diagonal Sum), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation
To solve this problem, we need to iterate through the elements of the given square matrix and calculate the sum of the primary diagonal and the secondary diagonal excluding the overlapping element. We can achieve this by maintaining two pointers for the primary diagonal and the secondary diagonal. We iterate through the matrix and update the sum based on the current element's position.
- For the primary diagonal, the indices of the elements are when
i == j. - For the secondary diagonal, the indices of the elements are when
i + j == n - 1, wherenis the size of the matrix.
After calculating the sum of both diagonals, we return the total sum as the result.
Time Complexity: O(n), where n is the size of the matrix. Space Complexity: O(1)
Solution Code
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) {
sum -= mat[n/2][n/2]; // Exclude the middle element if the matrix has an odd size
}
return sum;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1572 (Matrix Diagonal Sum)?
This page provides optimized solutions for LeetCode problem 1572 (Matrix Diagonal Sum) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1572 (Matrix Diagonal Sum)?
The time complexity for LeetCode 1572 (Matrix Diagonal Sum) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1572 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1572 in Java, C++, or Python.