Start learning free

LESSON 258 OF 287 · NESTED LOOPS OVER GRIDS

Diagonal Sum in Python: One Loop for Two Indexes

Practice Read the full explanation

Given a square grid of integers grid, with as many rows as columns, return the sum of the cells on its diagonal: the cells that go from the top-left corner to the bottom-right corner.

A grid is a list of rows, and each row is a list of integers. Rows are numbered from 0, top to bottom, and columns from 0, left to right. A cell is on the diagonal when its row number and its column number are the same: row 0 and column 0, row 1 and column 1, and so on.

 

Example 1:

Input: grid = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]
Output: 15
Explanation: The diagonal cells are 1, 5 and 9: 1 + 5 + 9 = 15.

Example 2:

Input: grid = [
  [7]
]
Output: 7
Explanation: A grid with one cell: that cell is the whole diagonal.

Example 3:

Input: grid = [
  [-1, 2],
  [3, -4]
]
Output: -5
Explanation: The diagonal cells are -1 and -4: -1 + (-4) = -5. The 2 and the 3 are not on the diagonal.

 

Constraints:

  • grid has n rows and n columns, with n at least 1.
  • Every value is an integer between -1000 and 1000; values can be negative.
STEP 1 OF 4
    Ctrl + Enter to check

    PYTHON · NESTED LOOPS OVER GRIDS

    Diagonal Sum in Python, explained

    Problem overview

    The method diagonalSum receives a square grid, grid: a list of rows with as many rows as columns. It returns the sum of the cells on the diagonal that goes from the top-left corner to the bottom-right corner. A cell is on the diagonal when its row number and its column number are the same: row 0 and column 0, row 1 and column 1, and so on.

    For rows [1, 2, 3], [4, 5, 6] and [7, 8, 9] the diagonal cells are 1, 5 and 9, so the answer is 15. For [[7]] the single cell is the whole diagonal: 7. For [[-1, 2], [3, -4]] the diagonal holds -1 and -4, so the answer is -5.

    Approach

    The earlier grid exercises visit every cell with two nested loops. This one doesn't need that. A diagonal cell has the same number for its row and its column, so a single index i is enough to name it: the cell is grid[i][i]. One loop that counts i from 0 to the last row visits exactly the diagonal cells, one per row.

    A second loop would visit every cell just to skip all but one per row. With n rows, one loop does n additions, while two nested loops would look at n * n cells.

    Step by step

    1. Create total = 0. No diagonal cell has been added yet.
    2. Loop i over range(len(grid)), one turn per row.
    3. Add grid[i][i] to total. The first [i] picks row i, and the second picks column i in that row.
    4. Return total after the loop, when every diagonal cell has been added.

    The solution in Python

    class Solution:
        def diagonalSum(self, grid: List[List[int]]) -> int:
            total = 0
            for i in range(len(grid)):
                total += grid[i][i]
            return total
    

    Python details:

    • Chained indexing. grid[i] is a list, and indexing it again with [i] gives one integer. Python evaluates left to right.
    • len(grid) is the number of rows, which for a square grid is also the number of columns, so i never goes past the last column.
    • A generator expression does the same in one line: sum(grid[i][i] for i in range(len(grid))) gives 15 for the first example. The explicit loop is the same idea with a visible counter.

    The other diagonal, from the top-right corner to the bottom-left, pairs row i with column n - 1 - i. For the 3 by 3 example it adds 3, 5 and 7, which is also 15. That one is a different problem, but it uses the same single loop.

    Complexity

    Time: O(n) for an n by n grid, one addition per row. Space: O(1), only total and i.

    Edge cases and common mistakes

    • A second loop. Nesting a loop over columns and testing row == col gives the right sum but does n * n steps for work that needs n.
    • Adding the whole row. grid[i] is a list, so total += grid[i] raises a TypeError. The second index selects the number.
    • Returning inside the loop gives only the first cell, grid[0][0].
    • One cell. [[7]] runs the loop once and returns 7.
    • Negative values. They are added as usual: [[-1, 2], [3, -4]] gives -5.
    • Non-square grids. The lesson guarantees a square grid. For a grid with fewer columns than rows, grid[i][i] would eventually raise an IndexError.

    Testing

    • [[1, 2, 3], [4, 5, 6], [7, 8, 9]] gives 15.
    • [[7]] gives 7.
    • [[-1, 2], [3, -4]] gives -5.
    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free