Given a m x n
matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
Could you please write a function that takes a 2D array (matrix) of integers as input and modifies it according to the following rules:
Here are a few examples to illustrate the expected behavior:
Example 1:
Input: [ [1,1,1], [1,0,1], [1,1,1] ] Output: [ [1,0,1], [0,0,0], [1,0,1] ]
Example 2:
Input: [ [0,1,2,0], [3,4,5,2], [1,3,1,5] ] Output: [ [0,0,0,0], [0,4,5,0], [0,3,1,0] ]
Example 3:
Input: [[1,2,3],[4,0,6],[7,8,9]] Output: [[1,0,3],[0,0,0],[7,0,9]]
Can you implement this in an efficient manner?
Let's dive into the 'Set Matrix Zeroes' problem. Given a matrix (a 2D array), if any element in the matrix is 0, we need to set its entire row and column to 0. We'll explore a couple of approaches.
The most straightforward approach is to iterate through the matrix. When we find a 0, we record the row and column indices. Then, in separate iterations, we'll set the corresponding rows and columns to 0.
Algorithm:
matrix[i][j] == 0
, store i
in a rows
set and j
in a cols
set.rows
set, and for each row r
, set all elements in matrix[r][:]
to 0.cols
set, and for each column c
, set all elements in matrix[:][c]
to 0.Code (Python):
python def set_matrix_zeroes_naive(matrix): rows = set() cols = set() m = len(matrix) n = len(matrix[0]) if m > 0 else 0
for i in range(m):
for j in range(n):
if matrix[i][j] == 0:
rows.add(i)
cols.add(j)
for row in rows:
for j in range(n):
matrix[row][j] = 0
for col in cols:
for i in range(m):
matrix[i][col] = 0
return matrix
Big O Analysis:
rows
and cols
sets storing row and column indices.We can optimize the space complexity to O(1) by utilizing the first row and first column of the matrix to store the row and column information (instead of using separate sets).
Algorithm:
matrix[i][j] == 0
, set matrix[i][0] = 0
and matrix[0][j] = 0
.matrix[0][j] == 0
, set the entire column j
to 0.matrix[i][0] == 0
, set the entire row i
to 0.Code (Python):
python def set_matrix_zeroes_optimal(matrix): m = len(matrix) n = len(matrix[0]) if m > 0 else 0 first_row_has_zero = False first_col_has_zero = False
# Check if first row has zero
for j in range(n):
if matrix[0][j] == 0:
first_row_has_zero = True
break
# Check if first col has zero
for i in range(m):
if matrix[i][0] == 0:
first_col_has_zero = True
break
# Mark rows and cols
for i in range(1, m):
for j in range(1, n):
if matrix[i][j] == 0:
matrix[i][0] = 0
matrix[0][j] = 0
# Use mark to set elements
for i in range(1, m):
for j in range(1, n):
if matrix[i][0] == 0 or matrix[0][j] == 0:
matrix[i][j] = 0
# Set first row and col
if first_row_has_zero:
for j in range(n):
matrix[0][j] = 0
if first_col_has_zero:
for i in range(m):
matrix[i][0] = 0
return matrix
Big O Analysis:
In summary, the optimal solution provides a space-efficient way to solve the Set Matrix Zeroes problem.