
Sponsored
Sponsored
This approach involves traversing the matrix and accessing diagonal elements using indices.
Primary Diagonal: For an element to be on the primary diagonal, its row index must be equal to its column index (i.e., mat[i][i]).
Secondary Diagonal: For an element to be on the secondary diagonal, the sum of its row index and column index must be equal to n-1 (i.e., mat[i][n-i-1]).
Time Complexity: O(n) since we traverse the matrix diagonals once.
Space Complexity: O(1) as we use a constant amount of extra space.
1function diagonalSum(mat) {
2 let n = mat.length;
3 let sum = 0;
4 for (let i = 0; i < n; i++) {
5 sum += mat[i][i];
6 if (i !== n - i - 1) {
7 sum += mat[i][n - i - 1];
8 }
9 }
10 return sum;
11}
12
13// Example usage
14const mat = [
15 [1, 2, 3],
16 [4, 5, 6],
17 [7, 8, 9]
18];
19console.log(diagonalSum(mat));The function iterates through the matrix indices to sum up primary and secondary diagonal elements, ensuring to exclude double-counting of any single middle element for odd-length matrices.
An alternative method is to calculate both diagonal sums and subtract the repeated center element if it exists. This approaches the same goal in a slightly different way by not thinking too much about the double-count case upfront during the main loop.
Time Complexity: O(n) because of the loop through the matrix diagonals.
Space Complexity: O(1) as we use constant additional space.
1
This approach calculates the primary and secondary diagonal sums separately. After the sums are obtained, it checks if the matrix is odd in size; if so, it subtracts the middle element from the total sum to correct the double counting.