Algorithms · Visualized

Matrix: Set Matrix Zeroes

Matrix & 2D

Rotations, traversals, and grid searches on 2D arrays.

If any cell in a matrix is 0, its entire row and column must be set to 0. Time: O(rows × cols) average, O(rows × cols) worst; space: O(1) — using the matrix itself as marker storage, instead of O(rows + cols) extra arrays.

Big-O: Classic O(m·n) sweeps and in-place tricks.

Set Matrix Zeroes

Matrix / 2D Array

If any cell in a matrix is 0, its entire row and column must be set to 0. Doing this naively risks zeroing out cells that then incorrectly trigger more zeroing. The efficient trick: use the matrix's own first row and first column as 'markers' to remember which rows/columns need zeroing, avoiding extra memory.

How Set Matrix Zeroes Works

  1. First, check separately whether the original first row and first column contain any zeros (remember this in two flags), since they'll be reused as marker space.
  2. Scan the rest of the matrix (excluding row 0 and column 0): whenever you find a 0 at position (i, j), mark it by setting the cell at (i, 0) and (0, j) to 0 — using row 0 and column 0 as marker space.
  3. Scan the matrix again (excluding row 0 and column 0): for each cell, check if its row marker (column 0) or column marker (row 0) is 0, and if so, set that cell to 0.
  4. Finally, using the two flags saved in step 1, zero out row 0 entirely if it originally had a zero, and zero out column 0 entirely if it originally had a zero.
  5. The matrix now correctly has every affected row and column zeroed, using no extra matrix.

Set Matrix Zeroes Worked Example

Input: [[1, 1, 1], [1, 0, 1], [1, 1, 1]]

Found a 0 at (1,1). Mark row0 col1 and row1 col0 as 0 (markers): [[1,0,1],[0,0,1],[1,1,1]]. Second pass: cell(0,0) unaffected (its own markers are non-zero at this stage)... Actually row1's marker (row1,col0=0) zeroes the whole row1; column1's marker (row0,col1=0) zeroes the whole column1. Final matrix: [[1,0,1],[0,0,0],[1,0,1]].

Matrix: Set Matrix ZeroesO(m·n)
Zero entire rows/columns that contain a 0.
1
1
1
1
0
1
1
1
1
Step 1 / 3
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
Set Matrix Zeroes: remember which rows/columns hold a 0, then zero them out.
Python · Matrix Algorithms in Code
def set_zeroes(m):
    rows, cols = set(), set()
    for r in range(len(m)):
        for c in range(len(m[0])):
            if m[r][c] == 0:
                rows.add(r)
                cols.add(c)
    for r in rows:
        for c in range(len(m[0])):
            m[r][c] = 0
    for c in cols:
        for r in range(len(m)):
            m[r][c] = 0
    return m

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

Set Matrix Zeroes Time & Space Complexity

BestO(rows × cols)
AverageO(rows × cols)
WorstO(rows × cols)
SpaceO(1) — using the matrix itself as marker storage, instead of O(rows + cols) extra arrays

When to Use Set Matrix Zeroes

  • Spreadsheet-style data invalidation: propagating a 'zero out' rule to whole rows/columns based on a trigger cell.
  • A classic space-optimization exercise, showing how to reuse existing structure instead of allocating new memory.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.