Problem overview
The method setZeroes receives an Array[Array[Int]] with m rows and n columns and returns Unit. Wherever the matrix holds a 0, the whole row and the whole column of that cell must become 0. The change happens in place, in the matrix that was passed in.
One rule matters: only the zeros that are in the matrix at the start count. A cell that turns into 0 during the process doesn't clear its own row and column. For this matrix:
0 2 3 4
5 0 7 8
9 10 11 12
the zeros in row 0, column 0 and row 1, column 1 clear rows 0 and 1 and columns 0 and 1, which gives:
0 0 0 0
0 0 0 0
0 0 11 12
The 11 and 12 stay, because the zeros in column 0 and column 1 of the last row were created by the clearing, not present at the start.
Approach: remember where the zeros are, then clear
The tempting first attempt scans the matrix and zeroes a row and a column as soon as it meets a 0. That breaks the rule above: the new zeros look exactly like the original ones, so the scan keeps meeting them and clears more and more. On the matrix above, this approach turns every cell into 0:
0 0 0 0
0 0 0 0
0 0 0 0
The fix is to separate looking from changing. A first pass only records which rows and which columns contain a zero. A second pass then sets to 0 every cell whose row or column was recorded. The records need one boolean per row and one per column, so the extra space is O(m + n), and each pass visits every cell once, so the time is O(m * n). These are the bounds the lesson asks for.
The lesson also mentions a follow-up with O(1) extra space, which stores the marks in the first row and first column of the matrix itself. It needs extra care for the zeros that are already in that row and column, and the solution below does not use it.
Step by step
- Store the dimensions.
mismatrix.length, the number of rows.nismatrix(0).length, the number of columns, which is the same for every row. - Create the marks.
zeroRowis an array ofmbooleans andzeroColone ofn, allfalse, made withArray.fill(m)(false).zeroRow(i)says whether rowihas a zero, andzeroCol(j)the same for columnj. - Visit every row with
i <- 0 until m. - Visit every column of that row with
j <- 0 until n. Together the two loops reach each cell once. - Test the cell:
if (matrix(i)(j) == 0). - Record it: set
zeroRow(i)andzeroCol(j)totrue. Several zeros can share a row or a column, and marking it again changes nothing. This first pass only reads the matrix, so nothing has been lost when it ends. - Start the second pass with another pair of loops over
iandj. - Clear a cell when its row or its column is marked:
if (zeroRow(i) || zeroCol(j)), and inside itmatrix(i)(j) = 0. That is exactly the set of cells the problem wants to become 0.
The solution in Scala
class Solution {
def setZeroes(matrix: Array[Array[Int]]): Unit = {
val m = matrix.length
val n = matrix(0).length
val zeroRow = Array.fill(m)(false)
val zeroCol = Array.fill(n)(false)
for (i <- 0 until m) {
for (j <- 0 until n) {
if (matrix(i)(j) == 0) {
zeroRow(i) = true
zeroCol(j) = true
}
}
}
for (i <- 0 until m) {
for (j <- 0 until n) {
if (zeroRow(i) || zeroCol(j)) {
matrix(i)(j) = 0
}
}
}
}
}
Scala details worth knowing:
Array.fill(m)(false). It builds anArray[Boolean]of lengthmwith the second argument as every element. ForzeroRowandzeroColthat gives allfalseto start with.- A
valarray can change its elements.val zeroRowfixes only the name. WritingzeroRow(i) = trueis allowed, becauseArrayis mutable. - Writing into the matrix changes the caller's array. Arrays are passed by reference, so
matrix(i)(j) = 0modifies the original rows, and the method needs no return value. - Indexing uses parentheses.
matrix(i)(j)is rowi, then columnj. Square brackets in Scala are for type parameters, as inArray[Boolean]. ==compares values.matrix(i)(j) == 0compares two integers, as expected. Noequalscall is needed.- Short-circuit
||. InzeroRow(i) || zeroCol(j), the second operand isn't evaluated when the first istrue. Either way the result is the same here.
Complexity
Time: O(m * n). The first pass reads each cell once, and the second pass writes at most each cell once. Creating the two boolean arrays costs O(m + n), which is smaller.
Space: O(m + n). The two boolean arrays are the only storage that grows with the input. The matrix is modified in place and no copy is made.
Edge cases and common mistakes
- No zeros at all.
[[1,2,3]]stays[[1,2,3]]: no mark is set, so the second pass changes nothing. - A single cell.
[[0]]stays[[0]]. - A single column. A column
1, 0, 3becomes all zeros, since the zero's row clears one cell and its column clears the other two. - Two zeros in one row. In
[[0,1,2,0],[3,4,5,2],[1,3,1,5]]the marks arezeroRow = true,false,falseandzeroCol = true,false,false,true. Row 0 and columns 0 and 3 become 0, and the result is[[0,0,0,0],[0,4,5,0],[0,3,1,0]]. - Clearing while scanning. The mistake described in the approach: zeroing a row and a column as soon as a 0 is found makes new zeros count, and everything ends up 0.
- Using one pass for both jobs. Marks must be complete before the first cell is changed. That is why the lesson uses two separate loop nests.
- Swapping
mandn.zeroRowhasmentries andzeroColhasn. On a non-square matrix, mixing them up throws anArrayIndexOutOfBoundsException.
Testing
[[1,1,1],[1,0,1],[1,1,1]]gives[[1,0,1],[0,0,0],[1,0,1]].[[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]].[[0,2,3,4],[5,0,7,8],[9,10,11,12]]gives[[0,0,0,0],[0,0,0,0],[0,0,11,12]].[[1,2,3]]gives[[1,2,3]].[[0]]gives[[0]].[[1],[0],[3]]gives[[0],[0],[0]].
