Start learning free

LESSON 263 OF 292 · NESTED LOOPS OVER GRIDS

Diagonal Sum in Swift: One Loop, Two Subscripts

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

    SWIFT · NESTED LOOPS OVER GRIDS

    Diagonal Sum in Swift, explained

    Problem overview

    The method diagonalSum receives grid, a square grid of integers with as many rows as columns, and returns the sum of the cells on its diagonal: the ones from the top-left corner to the bottom-right corner. A cell is on the diagonal when its row number and column number are equal: (0, 0), (1, 1), (2, 2) and so on. Values may be negative.

    For [[1, 2, 3], [4, 5, 6], [7, 8, 9]] the diagonal cells are 1, 5 and 9, and the answer is 15. A grid with one cell, [[7]], gives 7. For [[-1, 2], [3, -4]] the diagonal holds -1 and -4, and the answer is -5. The 2 and the 3 are not on the diagonal.

    Approach

    A first idea is two nested loops over every cell with an if row == col test. It works, but it visits all the cells just to ignore most of them. The condition tells more: a diagonal cell is described by one number, because its row and column are the same. A single index i gives the cell grid[i][i], and running i from 0 to the last row visits exactly the diagonal cells.

    So the method needs one loop and a running total. For a grid with n rows it adds n numbers instead of looking at n * n cells.

    Step by step

    1. Create total with var, starting at 0. It grows inside the loop.
    2. Loop over the indexes. for i in 0..<grid.count gives one turn per row. Because the grid is square, the same range also covers every column number.
    3. Add the diagonal cell. total += grid[i][i]. The first [i] picks row i, and the second picks column i in that row.
    4. Return total after the loop. By then every diagonal cell has been added, one per row.

    The solution in Swift

    class Solution {
        func diagonalSum(_ grid: [[Int]]) -> Int {
            var total = 0
            for i in 0..<grid.count {
                total += grid[i][i]
            }
            return total
        }
    }
    

    Swift details worth knowing:

    • grid[i][i] is two reads. The first gives the row, an [Int], and the second gives one Int from it.
    • The range is half-open. 0..<grid.count stops before grid.count, so the last index used is the last row. Using 0...grid.count would reach one past the end and crash at run time.
    • The square shape is an assumption. On a grid with fewer columns than rows, grid[i][i] would be out of range for some i, and Swift would stop the program. The lesson guarantees a square grid.
    • += on a var. total must be declared with var; a let constant can't be changed.

    Complexity

    Time is O(n) for an n by n grid, since the loop runs once per row and each pass does one addition. Space is O(1).

    Edge cases and common mistakes

    • One cell. [[7]] runs the loop once with i = 0 and returns 7.
    • Negative values. They are added like any number: [[-1, 2], [3, -4]] gives -5.
    • Nested loops with a missing test. Adding every cell would give the sum of the whole grid instead of the diagonal.
    • Mixing up the diagonals. This lesson asks for the top-left to bottom-right one. The other diagonal uses grid[i][n - 1 - i].
    • Looping over values. for row in grid does not say which row you are in. An index is needed to pick the column.

    Testing

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