Diagonal Matrix Sum
Given a square matrix represented as a 2D array, calculate the sum of the elements of both the main diagonal and the secondary diagonal. The matrix will always be a square (n x n dimensions), and your task is to determine the total sum of these diagonal elements.
[ [ 1 ] ]
Explanation. The matrix is 1x1, consisting of only one element which belongs to both diagonals.
[ [ 1, 2 ], [ 3, 4 ] ]
Explanation. The main diagonal elements are 1 and 4, sum is 5. The secondary diagonal elements are 2 and 3, sum is 5. Total sum is 10.
[ [ 5, 9, 1 ], [ 2, 8, 7 ], [ 4, 6, 3 ] ]
Explanation. The main diagonal elements are 5, 8, 3, sum is 16. The secondary diagonal elements are 1, 8, 4, sum is 13. Total sum is 29.
Follow-up: Can you optimize your solution to work in O(n) time complexity where n is the height of the matrix?
The matrix will have a size of at least 1x1 and will not exceed 100x100. All elements in the matrix will be integers.
- Views
- 2