Set entire row and column to 0 if an element in matrix is 0.
Problem Statement
Examples
Input: matrix = [[1, 1, 1], [1, 0, 1], [1, 1, 1]]
Output: [[1, 0, 1], [0, 0, 0], [1, 0, 1]]
Explanation: Any row or column containing a 0 has all its elements set to 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]]
Explanation: Any row or column containing a 0 has all its elements set to 0.
Complexity
Time Complexity: O(M * N)
Space Complexity: O(1)
Hints
Editorial & Approach
Problem Overview & Intuition
Instead of allocating additional memory for row and column markers, use matrix[i][0] and matrix[0][j] to record zeroes. Use a single boolean flag for the first column.
Step-by-Step Approach
- Scan the matrix and record zero occurrences in row 0 and column 0.
- Use
col0to record if column 0 contains any zeroes. - Iterate backwards from bottom-right to update cells based on row and column markers.
- Return
matrix.
Optimal Implementation (JavaScript)
function setZeroes(matrix) {
let col0 = 1;
const m = matrix.length, n = matrix[0].length;
for (let i = 0; i < m; i++) {
if (matrix[i][0] === 0) col0 = 0;
for (let j = 1; j < n; j++) {
if (matrix[i][j] === 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
for (let i = m - 1; i >= 0; i--) {
for (let j = n - 1; j >= 1; j--) {
if (matrix[i][0] === 0 || matrix[0][j] === 0) {
matrix[i][j] = 0;
}
}
if (col0 === 0) matrix[i][0] = 0;
}
return matrix;
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- Single cell matrix [0] or [1].
- Single row or single column matrix.
- Matrix with no zeroes.