
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
Through a direct approach that preemptively subtracts the center element from the total, this JavaScript implementation handles both primary and secondary diagonal elements with ease.