Array ( [0] => [1] => questions [2] => Arrays [3] => Diagonal-Sum ) Arrays | Diagonal Sum | THE INQUISITIVE





Diagonal Sum

LEVEL:Beginner

Description

Given a 2D array of elements. You have to find the diagonal sum of elements in given array. Note: Before applying check whether it’s possible or not.

Input Format

First line contains two integers M and N. Next M lines contains N integers separated by spaces.

Output Format

Print the diagonal sum value.


Example 1:

Input
3 3
1 2 3
4 5 6
7 8 9


Output
15
Example 2:

Input
2 2
1 2 
3 4
Output
5
Example 3:

Input
3 3
3 2 1
6 5 4
9 8 7


Output
15

oops

Login to see Discussion




Approach

Approach 1: Brute Force

Step-i) Initialize sum to 0
Step-ii) run loop from i=0 to iStep-iii)inside above loop run other loop from j=0 -> jStep-iv) if i equals to row - j -1 add that element to sum
Step-v) return the sum

Time Complexity: O(n^2)
Space Complexity: O(1)

Approach 2: Using Liner Approach

Step-i) Initialize sum to 0
Step-ii) run loop from i= 0 to iStep-iii)add element present at array[i][row-i-1] to sum
Step-iv) return the sum

Time Complexity: O(n)
Space Complexity: O(1)


Note :

Let us know if you can come up with a better approach, mail us at support@theinquisitive.in Your approach will be reviewed and posted with credits to you.

oops

Login to see Solution