Back to photostream

Matrix Diagonal Sum Leetcode Solution

Problem Statement

In Matrix Diagonal Sum problem a square matrix of integers is given. We have to calculate the sum of all the elements present at its diagonals i.e. elements at primary diagonal as well as secondary diagonal. Each element should be counted only once.

Example

mat = ,

,

]

25

Explanation:

 

Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25

Notice that element mat = 5 is counted only once

mat = ,

,

,

]

8

Explanation:

 

Diagonals sum: (1+1+1+1)+(1+1+1+1)=8.

Approach

 

In given square matrix we have to just add the diagonal elements and return its sum.

Lets see what will be the indices pattern in the matrix for diagonal elements. First if we see on the primary diagonal, its first element is on index i=0,j=0 and next element is on (i+1,j+1). Similarly last element will be on index (n-1,n-1) where n is the width of the given square matrix. All indices on this diagonal have i=j.

So we can iterate over this diagonal in a loop as follows:

 

1. Initialise i=0 and j=0.

2. Run a loop while i

 

www.tutorialcup.com/leetcode-solutions/matrix-diagonal-su...

19 views
0 faves
0 comments
Uploaded on October 14, 2021
Taken on December 16, 2020