Ctrl K

Sum of Both Diagonals

Easy
You are given a square n × n matrix grid. Add up every number on the main diagonal (top-left to bottom-right) and on the anti-diagonal (top-right to bottom-left). When n is odd, the two diagonals meet in the centre cell; count its value only once. Return the total.
Example 1
grid=[[2, 4, 6], [1, 3, 5], [8, 7, 9]] → 28

Main diagonal: 2 + 3 + 9; anti-diagonal: 6 + 8 (the centre 3 is already counted). Total 28.

Example 2
grid=[[1, 2], [3, 4]] → 10

In a 2×2 grid the diagonals do not cross: 1 + 4 + 2 + 3 = 10.

Example 3
grid=[[7]] → 7
Constraints
  • n == len(grid) == len(grid[i])
  • 1 ≤ n ≤ 100
  • 1 ≤ grid[i][j] ≤ 100
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsCrossword That Reads Both Ways EasyIsland Coastline Length EasyRepack the Tray EasyBlur the Pixels EasyPaint Bucket Tool Easy
loading Python…
Input
grid=[[2, 4, 6], [1, 3, 5], [8, 7, 9]]
Expected
28

Run checks the first 3 tests in your browser. Submit checks all 41 tests on the server, hidden ones included.