1572. Matrix Diagonal Sum LeetCode Solution
In this guide, you will get 1572. Matrix Diagonal Sum LeetCode Solution with the best time and space complexity. The solution to Matrix Diagonal Sum problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Matrix Diagonal Sum solution in C++
- Matrix Diagonal Sum solution in Java
- Matrix Diagonal Sum solution in Python
- Additional Resources

Problem Statement of Matrix Diagonal Sum
Given a square matrix mat, return the sum of the matrix diagonals.
Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.
Example 1:
Input: mat = [[1,2,3],
[4,5,6],
[7,8,9]]
Output: 25
Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25
Notice that element mat[1][1] = 5 is counted only once.
Example 2:
Input: mat = [[1,1,1,1],
[1,1,1,1],
[1,1,1,1],
[1,1,1,1]]
Output: 8
Example 3:
Input: mat = [[5]]
Output: 5
Constraints:
n == mat.length == mat[i].length
1 <= n <= 100
1 <= mat[i][j] <= 100
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(1)
1572. Matrix Diagonal Sum LeetCode Solution in C++
class Solution {
public:
int diagonalSum(vector<vector<int>>& mat) {
const int n = mat.size();
int ans = 0;
for (int i = 0; i < n; ++i) {
ans += mat[i][i];
ans += mat[n - 1 - i][i];
}
return n % 2 == 0 ? ans : ans - mat[n / 2][n / 2];
}
};
/* code provided by PROGIEZ */
1572. Matrix Diagonal Sum LeetCode Solution in Java
class Solution {
public int diagonalSum(int[][] mat) {
final int n = mat.length;
int ans = 0;
for (int i = 0; i < n; ++i) {
ans += mat[i][i];
ans += mat[n - 1 - i][i];
}
return n % 2 == 0 ? ans : ans - mat[n / 2][n / 2];
}
}
// code provided by PROGIEZ
1572. Matrix Diagonal Sum LeetCode Solution in Python
class Solution:
def diagonalSum(self, mat: list[list[int]]) -> int:
n = len(mat)
ans = 0
for i in range(n):
ans += mat[i][i]
ans += mat[n - 1 - i][i]
return ans if n % 2 == 0 else ans - mat[n // 2][n // 2]
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.