Grokking Data Structures & Algorithms for Coding Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
Problem 2: Matrix Diagonal Sum (easy)
Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Problem Statement

Given a square matrix (2D array), calculate the sum of its two diagonals.

The two diagonals in consideration are the primary diagonal that spans from the top-left to the bottom-right and the secondary diagonal that spans from top-right to bottom-left. If a number is part of both diagonals (which occurs only for odd-sized matrices), it should be counted only once in the sum.

Examples

  1. Example 1:
    • Input:
      [[1,2,3],
       [4,5,6],
       [7,8,9]]
      
    • Expected Output: 25
    • Justification: Summing up the two diagonals (1+5+9+3+7), we get 25. Please note that the element at [1][1] = 5 is counted only once.
  2. Example 2:
    • Input:
      [[1,0],
       [0,1]]
      
    • Expected Output: 2
    • Justification: The sum of the two diagonals is 1+1 = 2.
  3. Example 3:
    • Input:
      [[5]]
      
    • Expected Output: 5
    • Justification: Since there's only one element, it is the sum itself.

Constraints:

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

Try it yourself

Try solving this question here:

Python3
Python3

. . . .

.....

.....

.....

Like the course? Get enrolled and start learning!

Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible