← Whiteboard questions

Set Matrix Zeroes

Blank out every row and column that holds a zero

DSA, Medium, Math & Geometry

Which structure or algorithm, and what does it cost.

A control panel is a grid grid of sensor readings with r rows and c columns. A reading of 0 means a faulty sensor. Its whole row and its whole column go dark, which means they become 0. Write set_zeroes(grid). Change grid in place and return it. Decide what to blank from the original readings only. A 0 made by this rule does not make more rows and columns go dark.

Examples

Input grid = [[3, 5, 2], [4, 0, 6], [7, 8, 1]]
Output [[3, 0, 2], [0, 0, 0], [7, 0, 1]]
Why the 0 at row 1, column 1 blanks row 1 and column 1.
Input grid = [[2, 7, 0], [6, 1, 3]]
Output [[0, 0, 0], [6, 1, 0]]
Why a 0 on the top edge blanks the top row and the last column.
Input grid = [[4, 1, 7], [2, 9, 3]]
Output [[4, 1, 7], [2, 9, 3]]
Why with no zero in the grid, nothing changes.

Constraints

Your answer must contain

Target Aim for O(r * c) time. Try to use O(1) extra memory.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Blanking cells while you scan goes wrong, because a new zero looks like an old one. How can you tell which zeros were there at the start?

Hint 2 the approach

Find the rows and columns that need blanking first, and change cells only after that. Think about where you could keep that list.

Hint 3 the key step

Use the first row and column as the list. Mark them while scanning the rest, and note if they held a zero. Blank inner cells first, those two lines last.

Walkthrough

Full walkthrough brute force to best

Brute force

Copy the grid. For every 0 in the original, set its row and its column to 0 in the copy. Then copy back. If many cells are 0, each one costs O(r + c), so the time is O(r * c * (r + c)) and the extra memory is O(r * c).

Better method

Record which rows and which columns hold a 0, in two lists, during one pass. In a second pass, set every cell to 0 when its row or its column is on a list. This is O(r * c) time and O(r + c) extra memory.

Best method

Use the grid's own first row and first column as the two lists. First note whether the first row and the first column hold a 0 by themselves, because the marks will write over them. Then scan the other cells: a 0 at row i, column j sets the first cell of row i and the first cell of column j to 0. Next set every inner cell to 0 when its row mark or its column mark is 0. Last, blank the first row and first column if their flags say so. A mark is 0 exactly when its line must go dark, so the inner cells come out right. Doing the first row and column last keeps the marks safe until they are used.

Hand trace

Run on [[3, 5, 2], [4, 0, 6], [7, 8, 1]]. The first row and the first column hold no 0, so both flags are false. Scan the inner cells. The 0 at row 1, column 1 sets row 1, column 0 and row 0, column 1 to 0. The grid is [[3, 0, 2], [0, 0, 6], [7, 8, 1]]. Now set an inner cell to 0 if its marks say so. Row 1, column 2 gets 0 (its row mark is 0). Row 2, column 1 gets 0 (its column mark is 0). Row 2, column 2 stays 1. Both flags are false, so the first row and column stay as they are. The result is [[3, 0, 2], [0, 0, 0], [7, 0, 1]].

Code

def set_zeroes(grid):
    rows, cols = len(grid), len(grid[0])
    first_row_zero = any(v == 0 for v in grid[0])
    first_col_zero = any(grid[r][0] == 0 for r in range(rows))
    for r in range(1, rows):
        for c in range(1, cols):
            if grid[r][c] == 0:
                grid[r][0] = 0
                grid[0][c] = 0
    for r in range(1, rows):
        for c in range(1, cols):
            if grid[r][0] == 0 or grid[0][c] == 0:
                grid[r][c] = 0
    if first_row_zero:
        for c in range(cols):
            grid[0][c] = 0
    if first_col_zero:
        for r in range(rows):
            grid[r][0] = 0
    return grid

Time and memory

O(r * c) time, because the grid is scanned a fixed number of times. O(1) extra memory: two flags. The marks live in cells the grid already has.

Common mistakes

  • Setting cells to 0 during the first scan. New zeros look like old ones, and the zeros spread over the whole grid.
  • Blanking the first row and first column before the inner cells. The marks are lost, and inner cells stay wrong.
  • Leaving out the two flags. A 0 that was already in the first row or column is then mixed up with a mark.

Related problems

More Math & Geometry problems
Set Matrix Zeroes: hints, walkthrough and Python solution