
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.
1#include <stdio.h>
2
3int diagonalSum(int** mat, int n) {
4 int sum = 0;
5 for (int i = 0; i < n; i++) {
6 sum += mat[i][i];
7 if (i != n - i - 1) {
8 sum += mat[i][n - i - 1];
9 }
10 }
11 return sum;
12}
13
14int main() {
15 int* mat[3];
16 int row1[] = {1, 2, 3};
17 int row2[] = {4, 5, 6};
18 int row3[] = {7, 8, 9};
19 mat[0] = row1;
20 mat[1] = row2;
21 mat[2] = row3;
22 printf("%d\n", diagonalSum(mat, 3));
23 return 0;
24}The function iterates over the elements, and sums those at positions [i][i] for the primary diagonal and [i][n-i-1] for the secondary diagonal. It avoids double-counting the center element in an odd-length matrix.
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
In this Java solution, the matrix diagonals are individually summed, and the repeated center element is subtracted if the matrix has an odd width and height, ensuring no element is counted twice.