Set Matrix Zeroes
Difficulty: Medium
You're given an m x n grid. If a cell is 0, set its entire row and column to 0.
Modify the grid in place. Ideally, use only constant extra memory.
Examples
Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]
The single 0 sits at row 1, column 1, so all of row 1 and all of column 1 become 0.
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]]
Two zeros exist - at (0,0) and (0,3) - so rows 0 gets fully zeroed, and columns 0 and 3 get zeroed everywhere.
Constraints
m == matrix.length
n == matrix[i].length
1 <= m, n <= 200
-2^31 <= matrix[i][j] <= 2^31 - 1
Approach
The trap: zeroing cells as you scan creates new zeros that wrongly clear more rows and columns. So first record which rows and columns to zero, then apply it in a separate pass.
A simple way to record this is a set of row indexes and a set of column indexes, built in one scan. A second scan zeroes any cell whose row or column is in those sets.
To use only constant extra memory, use the grid's own first row and first column as the markers instead of sets. You only need two booleans to remember whether the first row and first column had a zero originally, since they're about to be overwritten as markers.
Solutions
Brute Force - Track Rows/Columns With Sets
Scan the grid once, adding every row and column that contains a 0 to a set. Scan again, zeroing any cell whose row or column is in a set.
function setZeroes(matrix) {
const rows = new Set();
const cols = new Set();
const m = matrix.length, n = matrix[0].length;
for (let r = 0; r < m; r++) {
for (let c = 0; c < n; c++) {
if (matrix[r][c] === 0) {
rows.add(r);
cols.add(c);
}
}
}
for (let r = 0; r < m; r++) {
for (let c = 0; c < n; c++) {
if (rows.has(r) || cols.has(c)) {
matrix[r][c] = 0;
}
}
}
}Time: O(m · n) · Space: O(m + n), for the row and column sets
Optimal - Use the First Row and Column as Markers
Instead of sets, use matrix[r][0] and matrix[0][c] to mark 'row r needs zeroing' and 'column c needs zeroing'. This overwrites the first row and column, so first save in two booleans whether they had a zero, and handle them last.
function setZeroes(matrix) {
const m = matrix.length, n = matrix[0].length;
let firstRowHasZero = false;
let firstColHasZero = false;
for (let c = 0; c < n; c++) if (matrix[0][c] === 0) firstRowHasZero = true;
for (let r = 0; r < m; r++) if (matrix[r][0] === 0) firstColHasZero = true;
// Use row 0 and column 0 as marker space for every other row/column
for (let r = 1; r < m; r++) {
for (let c = 1; c < n; c++) {
if (matrix[r][c] === 0) {
matrix[r][0] = 0;
matrix[0][c] = 0;
}
}
}
for (let r = 1; r < m; r++) {
for (let c = 1; c < n; c++) {
if (matrix[r][0] === 0 || matrix[0][c] === 0) {
matrix[r][c] = 0;
}
}
}
if (firstRowHasZero) for (let c = 0; c < n; c++) matrix[0][c] = 0;
if (firstColHasZero) for (let r = 0; r < m; r++) matrix[r][0] = 0;
}Time: O(m · n) · Space: O(1) extra space