Start learning free

LESSON 262 OF 285 · NESTED LOOPS OVER GRIDS

Diagonal Sum in Go: One Loop over a Square Grid

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 an array of rows, and each row is an array 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

    GO · NESTED LOOPS OVER GRIDS

    Diagonal Sum in Go, explained

    Problem overview

    The function diagonalSum receives grid, a square [][]int with as many rows as columns, and returns the sum of the cells on the diagonal that runs from the top-left corner to the bottom-right corner. A cell is on that diagonal when its row number and its column number are equal: (0, 0), (1, 1), (2, 2) and so on.

    For [[1, 2, 3], [4, 5, 6], [7, 8, 9]] the diagonal cells are 1, 5 and 9, and the answer is 15. For [[7]] the answer is 7, and for [[-1, 2], [3, -4]] it is -5: the cells -1 and -4 are on the diagonal, while the 2 and the 3 are not.

    Approach: one index does both jobs

    It is tempting to reach for two nested loops, as in the other grid lessons, and skip every cell whose row and column differ. That works but wastes effort: on an n by n grid it looks at n * n cells to use n of them.

    The diagonal cell of row i is always in column i, so a single index gives both coordinates. One loop over the row numbers, adding grid[i][i] each time, visits exactly the diagonal and nothing else.

    Step by step

    1. Create total with :=, starting at 0.
    2. Loop over the row numbers: for i := range grid. With one variable, range gives the indexes 0, 1, 2 and so on: one turn per row.
    3. Add the diagonal cell: total += grid[i][i]. The first [i] picks row i, and the second picks column i inside that row.
    4. Return total after the loop. By then every diagonal cell has been added, one per row.

    The solution in Go

    func diagonalSum(grid [][]int) int {
        total := 0
        for i := range grid {
            total += grid[i][i]
        }
        return total
    }
    

    Go details:

    • for i := range grid gives only the index of each element, because only one loop variable is named. That is what the code needs, since it looks the cells up itself.
    • Chained indexing. grid[i][i] first takes grid[i], a []int, then element i of it.
    • Index checks happen at run time. If a row were shorter than the number of rows, grid[i][i] would stop the program with index out of range. For a grid with two rows of one value each, [[1], [4]], the second turn fails with index out of range [1] with length 1. The lesson's grids are square, so this can't happen there.
    • Non-square grids don't always fail. A 2 by 3 grid such as [[1, 2, 3], [4, 5, 6]] doesn't panic and returns 6, the sum of 1 and 5. It is simply outside what the lesson asks.

    Edge cases and common mistakes

    • A one-cell grid. [[7]] runs the loop once and adds grid[0][0], so the answer is 7.
    • Negative values. They are added like any others: for [[-1, 2], [3, -4]] the sum is -1 + (-4) = -5.
    • Adding the wrong cells. Off-diagonal cells such as the 2 and the 3 above must not be counted. grid[i][i] can't reach them.
    • Nesting a second loop. A loop over columns inside the first would visit every cell and need an if i == j test. The answer would be the same, but the work is quadratic instead of linear.
    • Returning inside the loop. That would add only the first diagonal cell.

    Complexity

    Time: O(n) for an n by n grid, because the loop runs n times and each turn does one addition. Space: O(1), since only total and the loop index are kept.

    Testing

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