Problem overview
Given an m x n matrix of integers as an Array<IntArray>, the function setZeroes must set the entire row and the entire column of every zero to 0. It works in place and returns nothing. Only the zeros present at the start count: a cell that becomes 0 during the work must not clear its own row and column.
For the matrix with rows 1 1 1, 1 0 1, 1 1 1, the only zero is in row 1 and column 1, so the middle row and the middle column become zeros:
1 0 1
0 0 0
1 0 1
In the matrix with rows 0 2 3 4, 5 0 7 8, 9 10 11 12, the zeros at row 0, column 0 and at row 1, column 1 clear rows 0 and 1 and columns 0 and 1. The last row keeps 11 and 12:
0 0 0 0
0 0 0 0
0 0 11 12
Approach
The tempting plan is to scan the matrix and, at each zero, clear its row and column on the spot. That fails: the cells just cleared now look like zeros, and when the scan reaches them they clear their own rows and columns too. On the second example, this approach turns the whole matrix into zeros, although the last row should keep 11 and 12.
The fix is to separate remembering from clearing. The first pass only reads the matrix and writes down which rows and columns contain a zero. The second pass then clears every cell whose row or column was marked. Because the marks are complete before any cell changes, the new zeros can't cause extra clearing.
The marks cost O(m + n) extra space: one flag per row and one per column. The time is O(m * n), since each pass visits every cell once. The statement's follow-up shows that the first row and the first column of the matrix can hold the marks, which brings the extra space down to O(1). This lesson uses the separate flag arrays, which are simpler to get right.
Step by step
- Read the dimensions.
val m = matrix.sizeandval n = matrix[0].size. Every row has the same length, so the first row tells the number of columns. - Create the marks.
zeroRowis aBooleanArray(m)andzeroColis aBooleanArray(n). They start filled withfalse. The flagzeroRow[i]will say whether rowihas a zero, andzeroCol[j]the same for columnj. - First pass: loop over rows and columns. Two nested loops,
iover0 until mandjover0 until n, reach every cell once. This pass changes nothing in the matrix. - Test for a zero.
if (matrix[i][j] == 0)only fires for the zeros that are really there, since nothing has changed yet. - Mark. Set
zeroRow[i]andzeroCol[j]totrue. Several zeros can share a row or column, and marking it again changes nothing. - Second pass. Another pair of nested loops over every cell. All zeros are recorded now, so cells can change safely.
- Clear. If
zeroRow[i] || zeroCol[j], setmatrix[i][j] = 0. A cell becomes zero exactly when its row or its column held a zero at the start.
The solution in Kotlin
class Solution {
fun setZeroes(matrix: Array<IntArray>) {
val m = matrix.size
val n = matrix[0].size
val zeroRow = BooleanArray(m)
val zeroCol = BooleanArray(n)
for (i in 0 until m) {
for (j in 0 until n) {
if (matrix[i][j] == 0) {
zeroRow[i] = true
zeroCol[j] = true
}
}
}
for (i in 0 until m) {
for (j in 0 until n) {
if (zeroRow[i] || zeroCol[j]) {
matrix[i][j] = 0
}
}
}
}
}
Kotlin details worth knowing:
BooleanArray(m)creates an array ofmprimitive booleans, allfalse. LikewiseIntArray(n)is filled with zeros.valarrays are still mutable.val zeroRowstops the name from pointing at another array, butzeroRow[i] = truechanges an element, which is allowed.- The matrix is changed in place. The function receives the caller's row arrays, so writing
matrix[i][j] = 0changes the caller's matrix. That's why the function can return nothing. ||short-circuits. IfzeroRow[i]is true,zeroCol[j]is not even read.- Full
Intrange. The values can be anything fromInt.MIN_VALUEtoInt.MAX_VALUE. The code only compares with0and assigns0, so no arithmetic can overflow.
Complexity
Time is O(m * n): two passes over all cells. Extra space is O(m + n): the two flag arrays. The matrix is changed in place, with no copy.
Edge cases and common mistakes
- Clearing while scanning. As described above, clearing a row and column at the first zero spreads zeros to the whole matrix. On the matrix with rows
0 2 3 4,5 0 7 8,9 10 11 12, that version ends with every cell equal to0instead of keeping11and12. - No zeros. Both flag arrays stay
falseand the matrix is untouched: rows1 2 3and4 5 6stay as they are. - A 1 by 1 matrix.
[5]stays[5], and[0]stays[0]. - Extreme values. The matrix with rows
Int.MIN_VALUE 0and7 Int.MAX_VALUEbecomes rows0 0and7 0: the zero is in row 0 and column 1, so row 0 and column 1 are cleared and the7survives. - Assuming the first row tells the rows' count. It tells the number of columns. The number of rows is
matrix.size.
