↻one more pass.
Matrices · Medium

Set Matrix Zeroes: the idea to remember.

Set an entire row and column to zero wherever the original integer matrix contains a zero, in place.

Solve on LeetCode ↗

The core insight

Record original zero status for the first row and column, use their cells as markers, then apply the markers to the interior.

Why it works

Markers preserve which original rows and columns must be zeroed while two booleans retain the marker row and column status.

The mistake to avoid

Do not zero cells during the discovery pass. New zeros would incorrectly propagate.

Time: O(rows × columns)Space: O(1)

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

void setZeroes(int[][] a) {
    boolean rowZero = false, colZero = false;
    for (int c = 0; c < a[0].length; c++) if (a[0][c] == 0) rowZero = true;
    for (int r = 0; r < a.length; r++) if (a[r][0] == 0) colZero = true;
    for (int r = 1; r < a.length; r++) for (int c = 1; c < a[0].length; c++)
        if (a[r][c] == 0) { a[r][0] = 0; a[0][c] = 0; }
    for (int r = 1; r < a.length; r++) for (int c = 1; c < a[0].length; c++)
        if (a[r][0] == 0 || a[0][c] == 0) a[r][c] = 0;
    if (rowZero) Arrays.fill(a[0], 0);
    if (colZero) for (int[] row : a) row[0] = 0;
}

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.