Set Matrix Zeroes
Medium
Topics
Given an m x n matrix, if an element is 0 set its entire row and column to 0. LeetCode mutates in place; here return the modified matrix.
Example 1
original zerogets zeroed
Each original
0 clears its whole row and its whole column. The trap is doing it as you scan: a zero you just wrote would then clear more rows. The marks must be collected first, which is why the row and column flags are usually stashed in the matrix’s own first row and column.2D grid — one row per line.
Input: grid = [[1,1,1],[1,0,1],[1,1,1]] Output: [[1,0,1],[0,0,0],[1,0,1]]
Example 2
original zerogets zeroed
Input: grid = [[0,1],[1,1]] Output: [[0,0],[0,1]]
Constraints
- 1 <= m, n <= 200
- -2^31 <= matrix[i][j] <= 2^31 - 1
Editorial — intuition, approach, complexity and pitfalls
Intuition
First record which rows and columns contain a zero, then zero them out in a second pass. Doing it in one pass would spread zeros incorrectly.
Approach
- Scan the matrix, collecting the set of rows and columns that have a zero.
- In a second pass, zero any cell whose row or column was marked.
- (An O(1)-space variant uses the first row/column as the markers.)
Dry Run
grid 1 1 1
1 0 1
1 1 1
pass 1 scan for zeros, recording only POSITIONS: rows {1}, cols {1}
pass 2 write: any cell whose row is in rows or column is in cols becomes 0
answer 1 0 1 | 0 0 0 | 1 0 1
Two passes are not laziness, they are the correctness argument. Zero a row and a
column the moment you find a zero, and those fresh zeros are indistinguishable
from original ones when the scan reaches them -- the effect cascades. On this grid
that returns 1 0 0 | 0 0 0 | 0 0 0: the single zero has spread to eight cells
instead of five.
Recording positions rather than mutating is what separates "this cell was zero in
the input" from "this cell is zero now".
The sets cost O(m + n), which is the usual answer and is accepted. The O(1)-space
refinement stores the flags in the matrix's own first row and column, using one
extra scalar for the overlap at (0,0) -- worth naming if asked to do better,
though the bookkeeping is where it gets fiddly.Complexity
- Time — O(m*n): two passes over the grid.
- Space — O(m+n): the marked-row and column sets.
Common Pitfalls
- Collect all zero positions first — mutating during the first scan would cascade zeros wrongly.
Full Solution — all languages
class Solution:
def setZeroes(self, grid):
rows=set(); cols=set()
for i,row in enumerate(grid):
for j,v in enumerate(row):
if v==0: rows.add(i); cols.add(j)
for i in range(len(grid)):
for j in range(len(grid[0])):
if i in rows or j in cols: grid[i][j]=0
return gridimport java.util.*;
class Solution {
public int[][] setZeroes(int[][] grid) {
int R=grid.length,C=grid[0].length;
Set<Integer> rows=new HashSet<>(),cols=new HashSet<>();
for(int i=0;i<R;i++)for(int j=0;j<C;j++)if(grid[i][j]==0) {
rows.add(i);
cols.add(j);
}
for(int i=0;i<R;i++)for(int j=0;j<C;j++)if(rows.contains(i)||cols.contains(j))grid[i][j]=0;
return grid;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<vector<int>> setZeroes(vector<vector<int>>& grid) {
int R=grid.size(),C=grid[0].size();
set<int> rows,cols;
for(int i=0;i<R;i++)for(int j=0;j<C;j++)if(grid[i][j]==0) {
rows.insert(i);
cols.insert(j);
}
for(int i=0;i<R;i++)for(int j=0;j<C;j++)if(rows.count(i)||cols.count(j))grid[i][j]=0;
return grid;
}
};/**
* @param {number[][]} grid
* @return {number[][]}
*/ var setZeroes = function(grid) {
const rows={},cols={};
for(let i=0;i<grid.length;i++)for(let j=0;j<grid[0].length;j++)if(grid[i][j]===0) {
rows[i]=1;
cols[j]=1;
}
for(let i=0;i<grid.length;i++)for(let j=0;j<grid[0].length;j++)if(rows[i]||cols[j])grid[i][j]=0;
return grid;
};