
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.
1using System;
2
3class Program {
4 public static int DiagonalSum(int[][] mat) {
5 int n = mat.Length;
6 int sum = 0;
7 for (int i = 0; i < n; i++) {
8 sum += mat[i][i];
9 if (i != n - i - 1) {
10 sum += mat[i][n - i - 1];
11 }
12 }
13 return sum;
14 }
15
16 static void Main(string[] args) {
17 int[][] mat = {
18 new int[] {1, 2, 3},
19 new int[] {4, 5, 6},
20 new int[] {7, 8, 9}
21 };
22 Console.WriteLine(DiagonalSum(mat));
23 }
24}This C# program calculates the sum of the diagonals efficiently by iterating over the square matrix elements and adding the required diagonal elements.
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#include <vector>
int diagonalSum(const std::vector<std::vector<int>>& mat) {
int n = mat.size();
int primarySum = 0, secondarySum = 0;
for (int i = 0; i < n; i++) {
primarySum += mat[i][i];
secondarySum += mat[i][n - i - 1];
}
if (n % 2 == 1) {
primarySum -= mat[n / 2][n / 2];
}
return primarySum + secondarySum;
}
int main() {
std::vector<std::vector<int>> mat = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
std::cout << diagonalSum(mat) << std::endl;
return 0;
}This C++ solution acknowledges the potential double-counting of the center element during diagonal sum calculation and corrects it after the sum is originally calculated.