Set Matrix Zeroes
Medium matrix
Description
Constraints
1 <= rows, cols <= 200
Examples
Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]
Hints (1)
- Record which rows and columns contain a zero, then apply.
Solutions
Record rows and columns. · Time O(rows*cols) · Space O(rows+cols)
func setZeroes(matrix [][]int) [][]int {
n, m := len(matrix), len(matrix[0])
a := make([][]int, n)
rows, cols := map[int]bool{}, map[int]bool{}
for r := 0; r < n; r++ {
a[r] = append([]int{}, matrix[r]...)
for c := 0; c < m; c++ {
if matrix[r][c] == 0 {
rows[r] = true
cols[c] = true
}
}
}
for r := 0; r < n; r++ {
for c := 0; c < m; c++ {
if rows[r] || cols[c] {
a[r][c] = 0
}
}
}
return a
}
Record rows and columns. · Time O(rows*cols) · Space O(rows+cols)
function setZeroes(matrix) {
const a = matrix.map(r => [...r]);
const rows = new Set(), cols = new Set();
for (let r = 0; r < a.length; r++) for (let c = 0; c < a[0].length; c++) if (a[r][c] === 0) { rows.add(r); cols.add(c); }
for (let r = 0; r < a.length; r++) for (let c = 0; c < a[0].length; c++) if (rows.has(r) || cols.has(c)) a[r][c] = 0;
return a;
}
Record rows and columns. · Time O(rows*cols) · Space O(rows+cols)
function setZeroes($matrix) {
$rows = []; $cols = [];
foreach ($matrix as $r => $row) {
foreach ($row as $c => $v) { if ($v === 0) { $rows[$r] = true; $cols[$c] = true; } }
}
foreach ($matrix as $r => &$row) {
foreach ($row as $c => $v) { if (isset($rows[$r]) || isset($cols[$c])) { $row[$c] = 0; } }
}
return $matrix;
}
Record rows and columns. · Time O(rows*cols) · Space O(rows+cols)
def setZeroes(matrix):
a = [row[:] for row in matrix]
rows = {r for r, row in enumerate(a) for v in row if v == 0}
cols = {c for row in a for c, v in enumerate(row) if v == 0}
for r in range(len(a)):
for c in range(len(a[0])):
if r in rows or c in cols:
a[r][c] = 0
return a
Record rows and columns. · Time O(rows*cols) · Space O(rows+cols)
function setZeroes(matrix: number[][]): number[][] {
const a = matrix.map(r => [...r]);
const rows = new Set<number>(), cols = new Set<number>();
for (let r = 0; r < a.length; r++) for (let c = 0; c < a[0].length; c++) if (a[r][c] === 0) { rows.add(r); cols.add(c); }
for (let r = 0; r < a.length; r++) for (let c = 0; c < a[0].length; c++) if (rows.has(r) || cols.has(c)) a[r][c] = 0;
return a;
}
Create a free account to submit solutions, track progress and save problems.
Create account