Matrix Diagonal Sum
Given a square matrix (2D array), calculate the sum of the matrix diagonal elements. There are two diagonals in the matrix: the main diagonal (from the top-left to the bottom-right) and the secondary diagonal (from the top-right to the bottom-left). If the matrix has odd dimensions (e.g. 3x3, 5x5), the central element will be counted twice.
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
Explanation. Main diagonal: 1, 5, 9. Sum = 15; Secondary diagonal: 3, 5, 7. Sum = 15. Total = 15 + 15 - 5 (5 is counted twice) = 25.
[ [ -1, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 1 ] ]
Explanation. Main diagonal: -1, 0, 1. Sum = 0; Secondary diagonal: 0, 0, 0. Sum = 0. Total = 0 + 0 = 0.
[ [ 2, 9 ], [ 4, 2 ] ]
Explanation. Main diagonal: 2, 2. Sum = 4; Secondary diagonal: 9, 4. Sum = 13. Total = 4 + 13 - 2 (2 is counted twice) = 15.
Follow-up: Can you optimize your solution to run in O(n) time complexity?
1. The number of rows in the matrix equals the number of columns (n x n matrix). 2. 1 <= n <= 300 3. Each element in the matrix is an integer between -100 and 100.
- Views
- 3