73. Set Matrix Zeroes
Last updated
Was this helpful?
Last updated
Was this helpful?
Difficulty: Medium
- Tags: Array
, Matrix
, Simulation
Given an m x n
integer matrix matrix
, if an element is 0
, set its entire row and column to 0
's.
You must perform this operation in-place, without using extra space.
๐น Example 1:
Input:
Output:
๐น Example 2:
Input:
Output:
m == matrix.length
n == matrix[0].length
1 <= m, n <= 200
-2^31 <= matrix[i][j] <= 2^31 - 1
A straightforward solution using O(mn) space is probably not the best approach.
A simple improvement uses O(m + n) space, but can you devise a solution using constant space?
To solve this problem efficiently:
Naive Approach:
Use two auxiliary arrays rows
and cols
to store which rows and columns need to be set to 0
. This approach uses extra space.
Optimized Approach:
Use the matrix itself to track which rows and columns need to be zeroed.
Use the first row and first column of the matrix to store the state of other rows and columns.
If matrix[i][j]
is 0
, mark the first row and first column to indicate that the entire row and column need to be set to zero.
Step 1: Check the first row and first column:
If any element in the first row or column is 0
, mark the rowZero
or colZero
flag as true
.
Step 2: Mark rows and columns to be zeroed:
Traverse the matrix starting from matrix[1][1]
and mark the first row and first column to indicate that the corresponding row and column should be set to 0
.
Step 3: Zero out cells:
Traverse the matrix again to set cells to 0
based on the marks in the first row and column.
Step 4: Handle the first row and first column:
Set the first row and first column to 0
if needed (based on the flags rowZero
and colZero
).
O(m * n):
We traverse the matrix multiple times, each traversal takes O(m * n)
.
O(1):
We do not use any extra space for storing row or column markers, making this solution constant space.
You can find the full solution .