Overview
Given an m × n integer matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Constraints
1 <= m, n <= 200-2^31 <= matrix[i][j] <= 2^31 - 1- Use O(1) extra space (use the first row/column as markers).
Examples
setZeroes([ [1, 1, 1], [1, 0, 1], [1, 1, 1] ]); // => [[1,0,1],[0,0,0],[1,0,1]]
setZeroes([ [0, 1, 2, 0], [3, 4, 5, 2], [1, 3, 1, 5] ]); // => [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
Solution
Reveal solution
function setZeroes(matrix) {
const m = matrix.length, n = matrix[0].length;
let firstRowZero = false, firstColZero = false;
for (let j = 0; j < n; j++) if (matrix[0][j] === 0) firstRowZero = true;
for (let i = 0; i < m; i++) if (matrix[i][0] === 0) firstColZero = true;
for (let i = 1; i < m; i++) {
for (let j = 1; j < n; j++) {
if (matrix[i][j] === 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
for (let i = 1; i < m; i++) {
for (let j = 1; j < n; j++) {
if (matrix[i][0] === 0 || matrix[0][j] === 0) {
matrix[i][j] = 0;
}
}
}
if (firstRowZero) for (let j = 0; j < n; j++) matrix[0][j] = 0;
if (firstColZero) for (let i = 0; i < m; i++) matrix[i][0] = 0;
return matrix;
}Use the first row and first column as markers. Track whether they themselves need zeroing with two booleans. O(1) extra space.
Resources
matrix-zeroing.js
Matrix Zeroing
mediumcodingAlgorithmsMatrix
Overview
Given an m × n integer matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Constraints
1 <= m, n <= 200-2^31 <= matrix[i][j] <= 2^31 - 1- Use O(1) extra space (use the first row/column as markers).
Examples
setZeroes([ [1, 1, 1], [1, 0, 1], [1, 1, 1] ]); // => [[1,0,1],[0,0,0],[1,0,1]]
setZeroes([ [0, 1, 2, 0], [3, 4, 5, 2], [1, 3, 1, 5] ]); // => [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
Solution
Reveal solution
function setZeroes(matrix) {
const m = matrix.length, n = matrix[0].length;
let firstRowZero = false, firstColZero = false;
for (let j = 0; j < n; j++) if (matrix[0][j] === 0) firstRowZero = true;
for (let i = 0; i < m; i++) if (matrix[i][0] === 0) firstColZero = true;
for (let i = 1; i < m; i++) {
for (let j = 1; j < n; j++) {
if (matrix[i][j] === 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
for (let i = 1; i < m; i++) {
for (let j = 1; j < n; j++) {
if (matrix[i][0] === 0 || matrix[0][j] === 0) {
matrix[i][j] = 0;
}
}
}
if (firstRowZero) for (let j = 0; j < n; j++) matrix[0][j] = 0;
if (firstColZero) for (let i = 0; i < m; i++) matrix[i][0] = 0;
return matrix;
}Use the first row and first column as markers. Track whether they themselves need zeroing with two booleans. O(1) extra space.
Resources
NameTopicDifficulty
103 of 103 problems