LearnWithKiriti

Set Matrix Zeroes

đź’» Try it yourself first. Write your solution in Java, C++, Python or JavaScript and run it against hidden tests, right here. New: mock interview with Mr. Tock. Explain your approach out loud, he pushes you to improve it, then you code it. You get a scorecard at the end.
Play
On this page
  1. Revision notes
  2. Brute: Copy Grid
  3. Better: Marker Arrays
  4. Optimal: Markers Inside

Revision notes

Set Matrix Zeroes (online-test style)

Video: “Set Matrix Zeroes” on LearnWithKiriti (Kodee and Mr. Tock). Arrays series, episode 15. LeetCode 73, Medium. Taught as an online coding test: a clock per round (5:00, 5:00, then 8:00), thinking time counts, and the optimal grows out of the better solution.

If a cell is zero, set its whole row and column to zero, in place.

 1  2  3  4        1  0  0  4
 5  0  7  8   ->   0  0  0  0
 9 10 11 12        9  0  0 12
13 14  0 16        0  0  0  0
Folder Approach Time Extra space
Brute-CopyGrid/ Read zeros from a copy, write zeros into matrix (across the row, down the column) O(m·n·(m+n)) O(m·n)
Better-MarkerArrays/ rowMark (one boolean per row) + colMark (one per column), then fill O(m·n) O(m + n)
Optimal-MarkersInside/ Markers live in column 0 and row 0; rowZero / colZero saved first; borders filled last O(m·n) O(1)

Rebuild it

Mark the borders. Fill the inside. Borders last.

  • Zero as you go fails: new zeros look like old ones and spread. Never mark with -1: any int is a legal value.
  • The copy only answers “does this row have a zero?” and “does this column have a zero?”: one boolean each is enough.
  • Column 0 has one cell per row, row 0 has one cell per column: slide rowMark and colMark inside.
  • A marker only writes a zero where the answer already has one. Inner cells are never touched.
  • Save rowZero and colZero first (real border zeros, and the corner matrix[0][0] sits in both lines).
  • Inner cells first, borders LAST. Filling row 0 first turns every column marker into zero and wipes the grid.

Practise it on learnwithkiriti.com (sheet, notes, code in 4 languages, Shelf Bot animates your own code), or next to the video in the Kodee Practice Chrome extension (link in the video description).

See the pseudocode.md in each folder. Every program was compiled, run and tested (3x3, 3x4, 4x4, 1x1, 2x2, negatives, border zeros).

brute

Brute: Copy Grid

R1 Brute: read zeros from a copy

copy = a copy of matrix
for each row, col:
    if copy[row][col] == 0:
        for across = 0 to cols-1: matrix[row][across] = 0
        for down = 0 to rows-1:   matrix[down][col] = 0

Derivation: zero as you go fails. The new zeros look exactly like the original ones, so the scan keeps wiping more rows and columns until almost the whole grid is zero. We must remember which zeros were there at the start: a photo of the start, a copy. Read zeros from the copy, write zeros into matrix; the copy never changes, so new zeros cannot spread. Why not mark cells with -1: -1 is a legal value (the grid can hold any int, from -2^31 up). No value is free to be a marker. Check on [[1,1,1],[1,0,1],[1,1,1]]: the copy has a zero at (1, 1). Across zeros row 1, down zeros column 1: [[1,0,1],[0,0,0],[1,0,1]]. Complexity: O(m·n·(m+n)) time in the worst case, O(m·n) extra space (the copy).

SetZeroesBrute.java
import java.util.*;

public class SetZeroesBrute {
    static void setZeroesBrute(int[][] matrix) {
        int rows = matrix.length;
        int cols = matrix[0].length;
        int[][] copy = new int[rows][cols];
        for (int row = 0; row < rows; row++) {
            copy[row] = matrix[row].clone();
        }
        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < cols; col++) {
                if (copy[row][col] == 0) {
                    for (int across = 0; across < cols; across++) {
                        matrix[row][across] = 0;
                    }
                    for (int down = 0; down < rows; down++) {
                        matrix[down][col] = 0;
                    }
                }
            }
        }
    }

    static String show(Object o) {
        if (o instanceof int[]) return java.util.Arrays.toString((int[]) o);
        if (o instanceof long[]) return java.util.Arrays.toString((long[]) o);
        if (o instanceof boolean[]) return java.util.Arrays.toString((boolean[]) o);
        if (o instanceof Object[]) return java.util.Arrays.deepToString((Object[]) o);
        return String.valueOf(o);
    }

    public static void main(String[] args) {
        { int[][] matrix = new int[][]{{1, 1, 1}, {1, 0, 1}, {1, 1, 1}}; setZeroesBrute(matrix); System.out.println(show(matrix)); }
        { int[][] matrix = new int[][]{{0, 1, 2, 0}, {3, 4, 5, 2}, {1, 3, 1, 5}}; setZeroesBrute(matrix); System.out.println(show(matrix)); }
        { int[][] matrix = new int[][]{{1, 2, 3, 4}, {5, 0, 7, 8}, {9, 10, 11, 12}, {13, 14, 0, 16}}; setZeroesBrute(matrix); System.out.println(show(matrix)); }
        { int[][] matrix = new int[][]{{1}}; setZeroesBrute(matrix); System.out.println(show(matrix)); }
        { int[][] matrix = new int[][]{{0}}; setZeroesBrute(matrix); System.out.println(show(matrix)); }
        { int[][] matrix = new int[][]{{-1, 2}, {3, 0}}; setZeroesBrute(matrix); System.out.println(show(matrix)); }
        { int[][] matrix = new int[][]{{1, 2, 3, 4}, {5, 0, 7, 8}, {0, 10, 11, 12}, {13, 14, 15, 0}}; setZeroesBrute(matrix); System.out.println(show(matrix)); }
    }
}
better

Better: Marker Arrays

R2 Better: one boolean per row and per column

rowMark = rows x false;  colMark = cols x false
pass 1: for each row, col:
    if matrix[row][col] == 0: rowMark[row] = true;  colMark[col] = true
pass 2: for each row, col:
    if rowMark[row] or colMark[col]: matrix[row][col] = 0

Derivation: the copy only answered two questions. Does this row have a zero? Does this column have a zero? A whole grid for two yes/no questions is too much: one boolean per row and one per column is enough. Pass 1 only reads, so new zeros cannot spread. Check on [[0,1,2,0],[3,4,5,2],[1,3,1,5]]: rowMark = [T, F, F], colMark = [T, F, F, T]. (1, 1) holds 4, neither marked, so it stays. (1, 3) is in a marked column, so it becomes 0. Result [[0,0,0,0],[0,4,5,0],[0,3,1,0]]. Complexity: O(m·n) time, O(m + n) extra space.

SetZeroesBetter.java
import java.util.*;

public class SetZeroesBetter {
    static void setZeroesBetter(int[][] matrix) {
        int rows = matrix.length;
        int cols = matrix[0].length;
        boolean[] rowMark = new boolean[rows];
        boolean[] colMark = new boolean[cols];
        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < cols; col++) {
                if (matrix[row][col] == 0) {
                    rowMark[row] = true;
                    colMark[col] = true;
                }
            }
        }
        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < cols; col++) {
                if (rowMark[row] || colMark[col]) {
                    matrix[row][col] = 0;
                }
            }
        }
    }

    static String show(Object o) {
        if (o instanceof int[]) return java.util.Arrays.toString((int[]) o);
        if (o instanceof long[]) return java.util.Arrays.toString((long[]) o);
        if (o instanceof boolean[]) return java.util.Arrays.toString((boolean[]) o);
        if (o instanceof Object[]) return java.util.Arrays.deepToString((Object[]) o);
        return String.valueOf(o);
    }

    public static void main(String[] args) {
        { int[][] matrix = new int[][]{{1, 1, 1}, {1, 0, 1}, {1, 1, 1}}; setZeroesBetter(matrix); System.out.println(show(matrix)); }
        { int[][] matrix = new int[][]{{0, 1, 2, 0}, {3, 4, 5, 2}, {1, 3, 1, 5}}; setZeroesBetter(matrix); System.out.println(show(matrix)); }
        { int[][] matrix = new int[][]{{1, 2, 3, 4}, {5, 0, 7, 8}, {9, 10, 11, 12}, {13, 14, 0, 16}}; setZeroesBetter(matrix); System.out.println(show(matrix)); }
        { int[][] matrix = new int[][]{{1}}; setZeroesBetter(matrix); System.out.println(show(matrix)); }
        { int[][] matrix = new int[][]{{0}}; setZeroesBetter(matrix); System.out.println(show(matrix)); }
        { int[][] matrix = new int[][]{{-1, 2}, {3, 0}}; setZeroesBetter(matrix); System.out.println(show(matrix)); }
        { int[][] matrix = new int[][]{{1, 2, 3, 4}, {5, 0, 7, 8}, {0, 10, 11, 12}, {13, 14, 15, 0}}; setZeroesBetter(matrix); System.out.println(show(matrix)); }
    }
}
optimal

Optimal: Markers Inside

R3 Optimal: markers inside row 0 and column 0

rowZero = row 0 has a zero?      colZero = column 0 has a zero?
for row = 1 to rows-1, col = 1 to cols-1:
    if matrix[row][col] == 0: matrix[row][0] = 0;  matrix[0][col] = 0
for row = 1 to rows-1, col = 1 to cols-1:
    if matrix[row][0] == 0 or matrix[0][col] == 0: matrix[row][col] = 0
if rowZero: zero all of row 0
if colZero: zero all of column 0

Derivation: draw Round 2’s picture. rowMark stands left of the grid like an extra column, colMark sits on top like an extra row. The grid already has a column with one cell per row (column 0) and a row with one cell per column (row 0). Slide the markers inside. Why the markers do not break the grid:

  • Inner cells (row >= 1, col >= 1) are never written by a marker.
  • A marker only writes a zero where the answer already has one: the zero at (3, 2) writes matrix[0][2], and column 2 is all zero in the answer anyway. Same for column 0: the zero at (1, 1) writes matrix[1][0], and row 1 is zero in the answer.
  • Two things can go wrong. 1) Row 0 or column 0 may hold a real zero of its own: save that first in rowZero and colZero. 2) The corner matrix[0][0] sits in both marker lines, so it cannot answer for both; that is why there are two booleans, one for row 0 and one for column 0.
  • Order: mark from the inner cells only, fill the inner cells from the markers, and fill the borders LAST. Zero row 0 first and every column marker turns zero: the whole grid wipes out, like the trap. Check on [[1,2,3,4],[5,0,7,8],[9,10,11,12],[13,14,0,16]]: rowZero = colZero = false. (1, 1) marks matrix[1][0] and matrix[0][1]; (3, 2) marks matrix[3][0] and matrix[0][2]. Fill: rows 1 and 3, columns 1 and 2 become zero. Borders stay. Result [[1,0,0,4],[0,0,0,0],[9,0,0,12],[0,0,0,0]]. Complexity: O(m·n) time, O(1) extra space. No imports needed.
SetZeroes.java
import java.util.*;

public class SetZeroes {
    static void setZeroes(int[][] matrix) {
        int rows = matrix.length;
        int cols = matrix[0].length;
        boolean rowZero = false;
        boolean colZero = false;
        for (int col = 0; col < cols; col++) {
            if (matrix[0][col] == 0) {
                rowZero = true;
            }
        }
        for (int row = 0; row < rows; row++) {
            if (matrix[row][0] == 0) {
                colZero = true;
            }
        }
        for (int row = 1; row < rows; row++) {
            for (int col = 1; col < cols; col++) {
                if (matrix[row][col] == 0) {
                    matrix[row][0] = 0;
                    matrix[0][col] = 0;
                }
            }
        }
        for (int row = 1; row < rows; row++) {
            for (int col = 1; col < cols; col++) {
                if (matrix[row][0] == 0 || matrix[0][col] == 0) {
                    matrix[row][col] = 0;
                }
            }
        }
        if (rowZero) {
            for (int col = 0; col < cols; col++) {
                matrix[0][col] = 0;
            }
        }
        if (colZero) {
            for (int row = 0; row < rows; row++) {
                matrix[row][0] = 0;
            }
        }
    }

    static String show(Object o) {
        if (o instanceof int[]) return java.util.Arrays.toString((int[]) o);
        if (o instanceof long[]) return java.util.Arrays.toString((long[]) o);
        if (o instanceof boolean[]) return java.util.Arrays.toString((boolean[]) o);
        if (o instanceof Object[]) return java.util.Arrays.deepToString((Object[]) o);
        return String.valueOf(o);
    }

    public static void main(String[] args) {
        { int[][] matrix = new int[][]{{1, 1, 1}, {1, 0, 1}, {1, 1, 1}}; setZeroes(matrix); System.out.println(show(matrix)); }
        { int[][] matrix = new int[][]{{0, 1, 2, 0}, {3, 4, 5, 2}, {1, 3, 1, 5}}; setZeroes(matrix); System.out.println(show(matrix)); }
        { int[][] matrix = new int[][]{{1, 2, 3, 4}, {5, 0, 7, 8}, {9, 10, 11, 12}, {13, 14, 0, 16}}; setZeroes(matrix); System.out.println(show(matrix)); }
        { int[][] matrix = new int[][]{{1}}; setZeroes(matrix); System.out.println(show(matrix)); }
        { int[][] matrix = new int[][]{{0}}; setZeroes(matrix); System.out.println(show(matrix)); }
        { int[][] matrix = new int[][]{{-1, 2}, {3, 0}}; setZeroes(matrix); System.out.println(show(matrix)); }
        { int[][] matrix = new int[][]{{1, 2, 3, 4}, {5, 0, 7, 8}, {0, 10, 11, 12}, {13, 14, 15, 0}}; setZeroes(matrix); System.out.println(show(matrix)); }
    }
}