Problem overview
The method setZeroes receives an int[][] matrix with m rows and n columns. Wherever an element is 0, the whole row and the whole column of that element become 0. The change happens in place and nothing is returned. Only the zeros present at the start count: a cell that becomes 0 during the process does not clear its own row and column.
For [[1, 1, 1], [1, 0, 1], [1, 1, 1]] the only 0 is in row 1 and column 1, so the result is [[1, 0, 1], [0, 0, 0], [1, 0, 1]]. For [[0, 2, 3, 4], [5, 0, 7, 8], [9, 10, 11, 12]] the zeros clear rows 0 and 1 and columns 0 and 1, giving [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 11, 12]]. The 11 and 12 stay because no original zero lies in their row or column.
Approach: remember now, clear later
The tempting solution is to clear a row and a column the moment you meet a 0. That fails, because the zeros you write look exactly like original zeros when the scan reaches them, and they clear rows and columns that should have stayed. Running that approach on the 3 by 4 example above wipes the whole matrix to [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], not the expected result.
The fix is to split the work into two passes:
- Record. Scan the matrix without changing it. For each 0, note its row and its column.
- Clear. Scan again. A cell becomes 0 if its row or its column was noted.
The notes are two arrays of booleans, one entry per row and one per column. That is O(m + n) extra space, which is what the lesson asks for. Marking the same row twice does nothing, so several zeros in one row or column are no problem. The follow-up in the statement keeps the notes in the matrix's own first row and first column to reach O(1) space. That version has to handle the first row and column separately, and this lesson does not require it.
Step by step
- Read the dimensions.
m = matrix.lengthis the number of rows.n = matrix[0].lengthis the number of columns, because every row has the same length. - Create the marks.
boolean[] zeroRowhas sizemandboolean[] zeroColhas sizen. A new boolean array is full offalse, which is the right starting value: no row or column has a zero yet. - First pass. Two nested loops visit every
matrix[i][j]. This pass only reads the matrix. - Record each zero. When
matrix[i][j] == 0, setzeroRow[i]andzeroCol[j]totrue. - Second pass. Two more nested loops visit every cell again. All original zeros are recorded now, so changing cells loses nothing.
- Clear. If
zeroRow[i] || zeroCol[j]is true, setmatrix[i][j] = 0.
The solution in Java
class Solution {
public void setZeroes(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
boolean[] zeroRow = new boolean[m];
boolean[] zeroCol = new boolean[n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == 0) {
zeroRow[i] = true;
zeroCol[j] = true;
}
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (zeroRow[i] || zeroCol[j]) {
matrix[i][j] = 0;
}
}
}
}
}
The Java details worth a closer look:
- Method return type. The method is
void. A Java array is an object, and the method receives a reference to the caller's array, so assigning intomatrix[i][j]changes what the caller sees. - Default values.
new boolean[m]is filled withfalse, asnew int[m]is filled with 0, so no initialisation loop is needed. - Comparing with 0.
matrix[i][j] == 0compares primitiveintvalues, so==is the right operator here. - Short-circuit or. In
zeroRow[i] || zeroCol[j], Java skips the second test when the first is already true. Both are plain array reads, so the result is the same either way. - Full
intrange. The values can be anywhere from -2147483648 to 2147483647. The method never does arithmetic on them, only compares with 0 and assigns 0, so nothing can overflow. For[[-2147483648, 0], [4, 2147483647]]it returns[[0, 0], [4, 0]].
Complexity
Time: O(m * n). Each pass visits every cell once, so the method does two passes of m * n steps.
Space: O(m + n). The two boolean arrays hold one entry per row and one per column. The matrix itself is changed in place, with no copy.
Edge cases and common mistakes
- Clearing while scanning. New zeros are mistaken for original ones and spread further. That is why the first pass only records.
- No zeros.
[[5]]and[[1, 2, 3]]are returned unchanged, because no mark is ever set. - A single zero.
[[0]]stays[[0]]. - Several zeros in one row or column. Setting a mark that is already
truedoes no harm, so the example with two zeros in row 0,[[0, 1, 2, 0], [3, 4, 5, 2], [1, 3, 1, 5]], gives[[0, 0, 0, 0], [0, 4, 5, 0], [0, 3, 1, 0]]. - Swapping
mandn. The row marks needmatrix.lengthentries and the column marks needmatrix[0].length. With a non-square matrix, mixed-up sizes cause anArrayIndexOutOfBoundsException. - Using a value other than 0 as the marker. Writing a placeholder such as -1 into the matrix as a mark is not safe, since -1 is a legal value in the input. Separate boolean arrays avoid the problem.
Testing
[[1, 1, 1], [1, 0, 1], [1, 1, 1]]becomes[[1, 0, 1], [0, 0, 0], [1, 0, 1]].[[0, 1, 2, 0], [3, 4, 5, 2], [1, 3, 1, 5]]becomes[[0, 0, 0, 0], [0, 4, 5, 0], [0, 3, 1, 0]].[[0, 2, 3, 4], [5, 0, 7, 8], [9, 10, 11, 12]]becomes[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 11, 12]].[[5]]stays[[5]].[[0]]stays[[0]].
