Matrix Diagonal Sum - Array - Easy - LeetCode
💻 coding

Matrix Diagonal Sum - Array - Easy - LeetCode

1 min read 144 words
1 min read
ShareWhatsAppPost on X
  • 1The diagonal sum includes elements from both the primary and secondary diagonals of a square matrix.
  • 2Elements on the primary diagonal are counted once, while secondary diagonal elements are included only if they are not on the primary diagonal.
  • 3The algorithm has a time complexity of O(n) and a space complexity of O(1).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The diagonal sum includes elements from both the primary and secondary diagonals of a square matrix."

Matrix Diagonal Sum - Array - Easy - LeetCode

Given a square matrix mat, return the sum of the matrix diagonals.

Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.

Example 1:

Input: mat = [[1,2,3], [4,5,6], [7,8,9]] Output: 25 Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25 Notice that element mat[1][1] = 5 is counted only once. Example 2:

Input: mat = [[1,1,1,1], [1,1,1,1], [1,1,1,1], [1,1,1,1]] Output: 8 Example 3:

Input: mat = [[5]] Output: 5

Constraints:

n == mat.length == mat[i].length 1 <= n <= 100 1 <= mat[i][j] <= 100

public class Solution {
 public int DiagonalSum(int[][] mat) {
 int sum = 0;
 for(int i=0;i<mat.Length;i++){
 int j = mat.Length-i-1; 
 sum+=mat[i][i];
 if(j!=i){ 
 sum+=mat[i][j];
 } 
 j--;
 }
 
 return sum;
 }
}

Time Complexity: O(n)

Space Complexity: O(1)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 27 September 2020 · 1 min read · 144 words

Part of AskGif Blog · coding

You might also like