Set Matrix Zeroes
To solve this coding challenge, we need to update an \( m \times n \) matrix such that if an element is 0, its entire row and column are set to 0. The constraint is that it should be done
in place
without using extra space beyond O(1), which means modifying the matrix directly without using additional arrays or lists of size proportional to \( m \) or \( n \).
Explanation
Approach:
- Identify Rows and Columns with Zeroes:
- Iterate over the matrix to identify which rows and columns need to be set to zero.
- Instead of using extra storage, we can use the first row and the first column of the matrix itself to store this information.
-
Use two flags,
row_zero
col_zero
- Mark the Zeroes:
- During the iteration, if a cell contains zero, set the corresponding first row and first column cells to zero.
- Also, if the zero is in the first row or first column, set the respective flag to true.
- Update the Matrix:
- Iterate through the matrix again (excluding the first row and column), and for each cell, if its corresponding first row or first column cell is zero, set the cell to zero.
- Zero Out the First Row and Column:
-
Finally, check the
row_zero
col_zero
Detailed Steps in Pseudocode:
Step 1: Initialize Variables and Flags
# initialize dimensions of the matrix
rows = length(matrix)
cols = length(matrix[0])
# flags to check if first row or first column should be zeroed
row_zero = False
col_zero = False
Step 2: Identify Rows and Columns to be Zeroed
for i from 0 to rows - 1:
for j from 0 to cols - 1:
if matrix[i][j] == 0:
# mark the first cell of current row and column
matrix[0][j] = 0
matrix[i][0] = 0
# mark if the zero is in the first row or column
if i == 0:
row_zero = True
if j == 0:
col_zero = True
Step 3: Update the Matrix Based on Markers
for i from 1 to rows - 1:
for j from 1 to cols - 1:
if matrix[i][0] == 0 or matrix[0][j] == 0:
matrix[i][j] = 0
Step 4: Zero Out the First Row and Column if Needed
if row_zero:
for j from 0 to cols - 1:
matrix[0][j] = 0
if col_zero:
for i from 0 to rows - 1:
matrix[i][0] = 0