
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.
1def diagonalSum(mat):
2 n = len(mat)
3 total_sum = 0
4 for i in range(n):
5 total_sum += mat[i][i]
6 if i != n - i - 1:
7 total_sum += mat[i][n - i - 1]
8 return total_sum
9
10# Example usage
11matrix = [
12 [1, 2, 3],
13 [4, 5, 6],
14 [7, 8, 9]
15]
16print(diagonalSum(matrix))This Python function calculates the diagonal sum by iterating through each index of the square matrix and adding the appropriate diagonal elements, taking care to not double-count the middle element in 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.