Matrix Diagonal Sum - Problem
Matrix Diagonal Sum is a fundamental matrix manipulation problem that tests your understanding of 2D array indexing. Given a square matrix
The primary diagonal runs from top-left to bottom-right (elements where
Goal: Return the sum of all diagonal elements, counting the center element only once.
Input: A square matrix
Output: An integer representing the sum of diagonal elements
mat, you need to calculate the sum of elements on both diagonals.The primary diagonal runs from top-left to bottom-right (elements where
i == j), while the secondary diagonal runs from top-right to bottom-left (elements where i + j == n - 1). The key challenge is avoiding double-counting the center element in odd-sized matrices, where both diagonals intersect.Goal: Return the sum of all diagonal elements, counting the center element only once.
Input: A square matrix
mat of size n ร nOutput: An integer representing the sum of diagonal elements
Input & Output
example_1.py โ 3x3 Matrix
$
Input:
mat = [[1,2,3],[4,5,6],[7,8,9]]
โบ
Output:
25
๐ก Note:
Primary diagonal: 1 + 5 + 9 = 15. Secondary diagonal: 3 + 5 + 7 = 15. Center element 5 is counted twice, so total = 15 + 15 - 5 = 25.
example_2.py โ 4x4 Matrix
$
Input:
mat = [[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,1,1]]
โบ
Output:
8
๐ก Note:
Primary diagonal: 1 + 1 + 1 + 1 = 4. Secondary diagonal: 1 + 1 + 1 + 1 = 4. No center overlap in even-sized matrix, so total = 4 + 4 = 8.
example_3.py โ 1x1 Matrix
$
Input:
mat = [[5]]
โบ
Output:
5
๐ก Note:
Single element matrix - the only element is both on primary and secondary diagonal, but counted once. Result = 5.
Constraints
- n == mat.length == mat[i].length
- 1 โค n โค 100
- 1 โค mat[i][j] โค 100
- The matrix is always square
Visualization
Tap to expand
Understanding the Visualization
1
Identify Diagonals
Primary diagonal (โ): i==j positions. Secondary diagonal (โ): i+j==n-1 positions
2
Single Pass
For each row, access both mat[i][i] and mat[i][n-1-i] simultaneously
3
Handle Overlap
In odd-sized matrices, center element appears on both diagonals - subtract once
4
Return Sum
Total sum represents all diagonal elements counted exactly once
Key Takeaway
๐ฏ Key Insight: The optimal solution recognizes that we only need to visit diagonal elements, and cleverly handles the center overlap by subtracting it once when the matrix size is odd.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code