Set Matrix Zeroes

MediumMatrix · In-Place Markers🧩 Matrix TraversalLeetCode #73 ↗Updated

Problem

For an m × n integer grid, whenever a cell holds 0 its whole row and whole column must become 0. Only zeros present in the original grid count. Modify the grid in-place.
Input[[1,1,1],[1,0,1],[1,1,1]]Output[[1,0,1],[0,0,0],[1,0,1]]
Input[[0,1,2,0],[3,4,5,2],[1,3,1,5]]Output[[0,0,0,0],[0,4,5,0],[0,3,1,0]]

1 ≤ m, n ≤ 200  ·  -231 ≤ matrix[i][j] ≤ 231-1  ·  Follow-up: O(1) extra space.

Try it yourself

Java
class Solution {
    public void setZeroes(int[][] matrix) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Separate recording from writing: you only need one flag per row and per column — and row 0 / column 0 of the grid itself can hold those flags, as long as you first remember whether they had their own zeros.
PatternMatrix Traversal

Instinct A 2D grid you must walk in a fixed geometric order (spiral, diagonal, layer, rotate) or update in place - think boundaries, direction vectors and index maths.

Memory hack Walk the walls, then shrink the room - four fences (top, bottom, left, right) close in after every lap.

Open the Matrix Traversal guide →

Approaches

Brute ForceCopy Grid, Zero Row & Column per Zero

Time O(m·n·(m+n))Space O(m·n)

Read zeros from the untouched original but write into a copy, so newly written zeros can't cascade. For every zero found, wipe its row and column in the copy (O(m+n) each), then copy back.

Java
public void setZeroes(int[][] matrix) {
    int rows = matrix.length, cols = matrix[0].length;
    int[][] copy = new int[rows][];
    for (int r = 0; r < rows; r++) copy[r] = matrix[r].clone();
    for (int r = 0; r < rows; r++) {
        for (int c = 0; c < cols; c++) {
            if (matrix[r][c] == 0) {
                for (int k = 0; k < cols; k++) copy[r][k] = 0;
                for (int k = 0; k < rows; k++) copy[k][c] = 0;
            }
        }
    }
    for (int r = 0; r < rows; r++) System.arraycopy(copy[r], 0, matrix[r], 0, cols);
}

Correct, but a grid full of zeros costs O(mn(m+n)) time and O(mn) memory.

At a glance

LevelApproachTimeSpace
Brute ForceCopy Grid, Zero Row & Column per ZeroO(m·n·(m+n))O(m·n)
BetterRow & Column Flag ArraysO(m·n)O(m+n)
OptimalFirst Row/Column as MarkersO(m·n)O(1)
Common pitfalls
  • Zeroing in place while scanning — new zeros cascade and wipe the whole grid.
  • Zeroing row 0 / column 0 before the interior — destroys the markers.
  • Sharing matrix[0][0] for both row 0 and column 0 without a separate flag.
Interview tips
  • Explain why the result must depend only on original zeros.
  • Walk through O(mn) → O(m+n) → O(1) space as a deliberate progression.
  • Call out the processing order explicitly; it is the whole trick.
Pattern
Use the input as scratch space → O(1)-space follow-ups where row/column state fits in the grid's own border.
My notes saved in this browser