Problem overview
The method SetZeroes receives an int[][] matrix with m rows and n columns. Wherever an element is 0, its entire row and its entire column must become 0. The change happens in place and the method returns nothing. Only zeros that are in the matrix 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 zero is in row 1, column 1, so the middle row and the middle column become 0, giving {{1, 0, 1}, {0, 0, 0}, {1, 0, 1}}. The method should run in O(m * n) time and use O(m + n) extra space.
Approach: remember now, clear later
The tempting plan is to scan the matrix and zero a row and a column the moment a 0 is found. That breaks the rule above. The new zeros look exactly like original ones, so a later scan would clear rows and columns that should have stayed. In {{0, 2, 3, 4}, {5, 0, 7, 8}, {9, 10, 11, 12}}, the cells 11 and 12 must survive, but zeroing eagerly would turn row 2 into zeros as well.
The fix is to split the work into two passes:
- A read-only pass that records which rows and which columns contain a zero.
- A write pass that zeroes every cell whose row or column was recorded.
Two boolean arrays hold the records: one entry per row and one per column. That is m + n flags, which meets the O(m + n) space limit. Several zeros can share a row or column, and flagging it again changes nothing.
The follow-up asks for O(1) extra space. The idea there is to keep the flags inside the matrix itself, in its first row and first column, which then need separate handling. This lesson uses the straightforward flag arrays.
As a small check, take the matrix {{0, 1, 2, 0}, {3, 4, 5, 2}, {1, 3, 1, 5}}. The first pass finds zeros at row 0, column 0 and row 0, column 3, so only zeroRow[0], zeroCol[0] and zeroCol[3] are true. The second pass then clears row 0 and columns 0 and 3, and leaves the middle values 4, 5, 3 and 1 alone.
The follow-up has one catch worth knowing. If the first row and first column store the marks for the others, a zero that was already in the first row or column would be confused with a mark. So the constant-space version first records, in two extra variables, whether the first row and the first column contained a zero themselves, and clears them last.
Step by step
- Store the dimensions:
m = matrix.Lengthrows andn = matrix[0].Lengthcolumns. Every row has the same length, so the first row gives the column count. - Create
zeroRow(sizem) andzeroCol(sizen). A newbool[]starts with every elementfalse, which means "no zero seen yet". - First pass. Two nested loops visit every cell. When
matrix[i][j] == 0, setzeroRow[i]andzeroCol[j]totrue. This pass changes nothing inmatrix. - Second pass. Two more nested loops visit every cell again. If
zeroRow[i] || zeroCol[j], setmatrix[i][j]to 0.
The solution in C#
class Solution {
public void SetZeroes(int[][] matrix) {
int m = matrix.Length;
int n = matrix[0].Length;
bool[] zeroRow = new bool[m];
bool[] zeroCol = new bool[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;
}
}
}
}
}
C# details worth knowing:
- Default values. Arrays of
boolare filled withfalseand arrays ofintwith 0 when created, so no initialization loop is needed. - Jagged array.
int[][]is an array of row arrays. The row count ismatrix.Lengthand the column count ismatrix[0].Length. Cells are read asmatrix[i][j]. A rectangularint[,]would useGetLength(0)andGetLength(1)instead. voidand in-place work. Arrays are reference types, so the caller'smatrixsees every assignment made throughmatrix[i][j] = 0.- Both dimensions come from the data. A matrix with 2 rows and 2 columns has
matrix.Lengthequal to 2 andmatrix[0].Lengthequal to 2, so it is easy to mix the two up on square inputs. Takingnfrommatrix[0].Lengthkeeps the code correct for any rectangle. - The test is
== 0only. Any other value, positive or negative, is not a zero, so the first pass ignores it. The second pass overwrites cells with 0 whatever they held.
Complexity
Time: O(m * n). Each pass visits every cell once.
Space: O(m + n). The two flag arrays hold m and n booleans. The matrix itself is changed in place, with no copy.
Edge cases and common mistakes
- No zeros.
{{1, 2}, {3, 4}}stays as it is, because no flag is ever set. - A single cell.
{{0}}stays{{0}}. - Zeros in the first row or column.
{{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}}. The flag arrays make this case need no special code. - Zeros created along the way.
{{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}}. The cells11and12stay because only the original zeros were recorded. - Zeroing during the first pass. This is the classic mistake: new zeros get mistaken for original ones and clear too much.
- Swapping
mandn. A non-square matrix then indexes outside an array and throwsIndexOutOfRangeException.
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}}.{{1, 2}, {3, 4}}is unchanged.{{0}}is unchanged.
