Set Matrix Zeroes solution explained

To set matrix zeroes in place with constant extra space, use the first row and first column of the grid as marker storage: first record whether that row and column themselves contain a zero, then mark row r and column c by writing zeros into grid[r][0] and grid[0][c], clear the inner cells using those marks, and clear the first row and column last. The Set Matrix Zeroes solution takes O(m·n) time and O(1) extra space.

By Published 7 min read

The task, restated

You receive a rectangular grid of integers. Every cell that holds a zero in the original grid spreads: its entire row and its entire column become zero. Only zeros that were there at the start count; a cell you just cleared does not spread further. Modify the grid in place.

Examples made up for this page
BeforeAfter
[[5, 1, 0], [2, 7, 3], [0, 4, 6]][[0, 0, 0], [0, 7, 0], [0, 0, 0]]
[[0, 2, 3], [4, 5, 6]][[0, 0, 0], [0, 5, 6]]
[[3, 8, 1, 6], [2, 0, 5, 7], [4, 9, 6, 0]][[3, 0, 1, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
[[9]][[9]]
Examples made up for this page. Scroll sideways on a small screen.

The first example is a useful one to trace: only the cell holding 7 survives, because its row and column contain no original zero. Ask whether the grid can be empty, whether extra memory is allowed, and whether values can be negative (they can; only zero matters).

How interviewers use it

Set Matrix Zeroes is a memory-ladder question. Almost everyone reaches the version with two sets. The interviewer then asks for constant extra space, and the real test begins: can you reuse the input as storage without corrupting the information you still need? Watch for the follow-up about why the first row and column need special flags.

  • Use one flag instead of two. Keep a flag for the first column only, let grid[0][0] stand for the first row, and process the rows bottom-up. Fewer variables, more care.
  • The grid is huge and stored by rows on disk. Two passes over rows with the two-set version streams nicely; the marker version needs random access to the first row.
  • Spread only one step, to the four neighbors. A different problem: record originals first, then update neighbors.
  • Count how many cells end up zero without changing the grid. Count marked rows a and columns b; the answer is a·n + b·m - a·b.

First idea, and why it fails: zero as you go

Scanning and immediately clearing the row and column of each zero breaks the rule. The cells you clear are now zeros too, and when the scan reaches them they spread again, wiping out most of the grid. The fix is to separate reading from writing. The simplest correct version copies the grid, reads from the copy and writes to the original: O(m·n) extra space.

Better: remember rows and columns in two sets

You do not need the whole copy. You only need to know which rows and which columns had a zero. One pass collects them into two sets, a second pass clears every cell whose row or column is in a set. O(m·n) time and O(m + n) extra space.

def zero_with_sets(grid):
    rows, cols = set(), set()
    for r, line in enumerate(grid):
        for c, v in enumerate(line):
            if v == 0:
                rows.add(r)
                cols.add(c)
    for r, line in enumerate(grid):
        for c in range(len(line)):
            if r in rows or c in cols:
                line[c] = 0
Two sets: O(m·n) time, O(m + n) space. Used as the test oracle.

Optimal: store the marks in the first row and column

The first column has one slot per row, and the first row has one slot per column, which is exactly the shape of the two sets. So use them. Writing a zero into grid[r][0] means "row r must be cleared", and a zero in grid[0][c] means "column c must be cleared". Any cell that gets cleared this way was going to become zero anyway, so the marks lose no information about the inner grid.

The first row and column are the exception: once you write marks into them, you can no longer tell whether they held an original zero. So check that first, into two booleans. Then mark from the inner cells, clear the inner cells from the marks, and only at the end clear the first row and column if their booleans say so. Clearing them earlier would erase the marks you still need.

def zero_in_place(grid):
    m, n = len(grid), len(grid[0])
    first_col_zero = any(grid[r][0] == 0 for r in range(m))
    first_row_zero = any(grid[0][c] == 0 for c in range(n))
    for r in range(1, m):
        for c in range(1, n):
            if grid[r][c] == 0:
                grid[r][0] = 0
                grid[0][c] = 0
    for r in range(1, m):
        for c in range(1, n):
            if grid[r][0] == 0 or grid[0][c] == 0:
                grid[r][c] = 0
    if first_row_zero:
        for c in range(n):
            grid[0][c] = 0
    if first_col_zero:
        for r in range(m):
            grid[r][0] = 0
Python: in-place markers. O(m·n) time, O(1) extra space.
function zeroInPlace(grid) {
  const m = grid.length, n = grid[0].length;
  const firstColZero = grid.some((row) => row[0] === 0);
  const firstRowZero = grid[0].includes(0);
  for (let r = 1; r < m; r++) {
    for (let c = 1; c < n; c++) {
      if (grid[r][c] === 0) {
        grid[r][0] = 0;
        grid[0][c] = 0;
      }
    }
  }
  for (let r = 1; r < m; r++) {
    for (let c = 1; c < n; c++) {
      if (grid[r][0] === 0 || grid[0][c] === 0) grid[r][c] = 0;
    }
  }
  if (firstRowZero) grid[0].fill(0);
  if (firstColZero) for (const row of grid) row[0] = 0;
}
JavaScript: same order of steps; fill clears the first row in one call.

Time and space

Complexity for an m by n grid
VersionTimeExtra space
Copy the grid, read from the copyO(m·n)O(m·n)
Two sets of row and column indexesO(m·n)O(m + n)
First row and column as markersO(m·n)O(1)
Complexity for an m by n grid. Scroll sideways on a small screen.

Edge cases

  • A zero in the first row or first column, the case the two booleans exist for.
  • A zero at grid[0][0], which sets both booleans.
  • A single row or a single column: the inner loops do nothing, and the booleans do all the work.
  • No zeros at all: nothing changes.
  • Every cell zero.
  • Negative values, which are not special.

Mistakes to avoid

  • Clearing rows and columns during the first scan, which spreads zeros that were never in the input.
  • Starting the marking loops at index 0, which mixes original zeros in the first row with marks.
  • Clearing the first row or column before the inner cells, which wipes the marks.
  • Forgetting to check the first row and column before marking them.
  • Assuming the grid is square. Use separate m and n.

How to explain it out loud

Fictional example

Walking the interviewer from sets to markers
Candidate
If I clear as I scan, cleared cells spread again, so I record first and write second. Two sets of row and column numbers do that in m plus n space.
Candidate
For constant space, the first column has a slot per row and the first row a slot per column, so I can store the marks there. Cells I mark were going to be zero anyway.
Candidate
The first row and column lose their own history when I mark them, so I save two booleans at the start and clear them last. Everything is m times n time.

Rotate Image and Spiral Matrix are the other two grid problems in this set; one tests index mapping, the other boundary tracking. Meeting Rooms II is another case where splitting the data into two simpler lists, starts and ends rather than rows and columns, makes the problem easy.

Where Natively fits

In practice sessions on your Mac or Windows PC, Natively can read this kind of grid problem from a screenshot and suggest the step from two sets to in-place markers, including why the first row needs its own flag. Because it transcribes the mock round, you can review whether you explained the order of the passes clearly. See the AI interview assistant.

Questions people ask

How do you solve Set Matrix Zeroes in constant space?

Save whether the first row and first column contain a zero, use them to mark which rows and columns to clear, clear the inner cells from those marks, and clear the first row and column last.

Why can't you zero rows and columns while scanning?

The cells you clear look like original zeros when the scan reaches them, so they spread further. Record first, then write.

What is the time complexity of Set Matrix Zeroes?

O(m times n) for every version. The space is O(m plus n) with two sets and O(1) with the in-place markers.

Why does the first row need its own flag?

Once you write marks into the first row and column, you can no longer tell whether they held an original zero, so you record that before marking.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP