Given a square matrix of size n * n. Your task is to calculate the sum of its diagonals. When n is odd, there is a center value which is counted twice in the diagonal sum.
[Naive Approach] Traverse Entire Matrix - O(n^2) Time O(1) Space
The idea is to traverse every cell of the matrix and separately check whether it belongs to the primary diagonal or the secondary diagonal. Since the checks are performed independently, the center element of an odd-sized matrix gets counted twice, as required by the problem.
Output
10
Time Complexity: O(n^2) Auxiliary Space: O(1)
[Expected Approach] Traverse Only Diagonals - O(n) Time O(1) Space
The idea is to iterate through each row and directly add the primary diagonal element mat[i][i] and the secondary diagonal element mat[i][n-i-1]. For odd-sized matrices, the center element naturally gets counted twice as required.
Let us understand with example: Input: mat[][] = [[1, 2], [3, 4]]
Initially, sum = 0.
First loop adds primary diagonal elements: sum = 0 + 1 + 4 = 5
Second loop adds secondary diagonal elements: sum = 5 + 2 + 3 = 10