Set Matrix Zeros
JavaView on GFG
Time: O(n*m)
Space: O(1)
Advertisement
Intuition
Set entire row and column to 0 if any element is 0. In-place O(1) space using first row/col as markers.
Algorithm
- 1First pass: mark which rows and columns need zeroing using first row and col. Second pass: zero marked rows/cols.
Common Pitfalls
- •Same as LC 73. Track if first row/col themselves contain zero separately. O(mn) time O(1) space.
Set Matrix Zeros.java
Java
// Approach: Use first row/column as flags to mark which rows/columns should be zeroed; zero them in second pass.
// Time: O(n*m) Space: O(1)
class Solution {
public void setMatrixZeroes(int[][] mat) {
int n = mat.length;
int m = mat[0].length;
int col0 = 1;
// step 1: Traverse the matrix and
// mark 1st row & col accordingly:
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (mat[i][j] == 0) {
// mark i-th row:
mat[i][0] = 0;
// mark j-th column:
if (j != 0)
mat[0][j] = 0;
else
col0 = 0;
}
}
}
// Step 2: Mark with 0 from (1,1) to (n-1, m-1):
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
if (mat[i][j] != 0) {
// check for col & row:
if (mat[i][0] == 0 || mat[0][j] == 0)
mat[i][j] = 0;
}
}
}
// step 3: Finally mark the 1st col & then 1st row:
if (mat[0][0] == 0) {
for (int j = 0; j < m; j++)
mat[0][j] = 0;
}
if (col0 == 0) {
for (int i = 0; i < n; i++)
mat[i][0] = 0;
}
}
}Advertisement
Was this solution helpful?