Set Matrix Zeroes medium
Problem Statement
Given an m x n
integer matrix matrix
, if an element is 0, set its entire row and column to 0. You must do it in place.
Example 1
Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]
Example 2
Input: matrix = [[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]]
Steps and Explanation
The naive approach would be to iterate through the matrix, and whenever we find a 0, iterate again to set all elements in that row and column to 0. This has a time complexity of O(mn (m+n)). To improve this, we'll use the first row and first column as markers.
-
Marker Rows and Columns: We use the first row and the first column to store information about whether a row or column needs to be zeroed. If we find a
0
atmatrix[i][j]
, we setmatrix[i][0]
andmatrix[0][j]
to0
. This acts as a flag. -
Iterate: We iterate through the matrix from
matrix[1][1]
tomatrix[m-1][n-1]
. Ifmatrix[i][j]
is 0, then we setmatrix[i][0]
andmatrix[0][j]
to 0. -
Zero Rows and Columns: After the iteration, we use the first row and column as markers. If
matrix[i][0]
is 0, we set the entirei
-th row to 0. Similarly, ifmatrix[0][j]
is 0, we set the entirej
-th column to 0. -
Handle First Row and Column: Finally, we handle the first row and column separately, based on whether
matrix[0][0]
is 0.
This approach reduces the time complexity significantly because we only iterate through the matrix a constant number of times.
Code (Java)
class Solution {
public void setZeroes(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
boolean firstRowZero = false;
boolean firstColZero = false;
// Check if the first row and column need to be zeroed
for (int i = 0; i < m; i++) {
if (matrix[i][0] == 0) {
firstColZero = true;
break;
}
}
for (int j = 0; j < n; j++) {
if (matrix[0][j] == 0) {
firstRowZero = true;
break;
}
}
// Mark rows and columns to be zeroed
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (matrix[i][j] == 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
// Zero rows and columns based on markers
for (int i = 1; i < m; i++) {
if (matrix[i][0] == 0) {
for (int j = 0; j < n; j++) {
matrix[i][j] = 0;
}
}
}
for (int j = 1; j < n; j++) {
if (matrix[0][j] == 0) {
for (int i = 0; i < m; i++) {
matrix[i][j] = 0;
}
}
}
//Handle first row and column
if(firstRowZero){
for(int j=0; j<n; j++) matrix[0][j] = 0;
}
if(firstColZero){
for(int i=0; i<m; i++) matrix[i][0] = 0;
}
}
}
Complexity
- Time Complexity: O(m*n) - We iterate through the matrix twice.
- Space Complexity: O(1) - We use constant extra space. We modify the matrix in place.