- Published on
Set Matrix Zeroes Leetcode Solution
- Authors
- Name
- QuickFeed
- @sahul_22_jr
Problem Statement
Given a matrix if an element in the matrix is 0 then you will have to set its entire column and row to 0 and then return the matrix.
Solution
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
const int m = matrix.size(); // Get the number of rows
const int n = matrix[0].size(); // Get the number of columns
// Flags to check if the first row or column needs to be filled with zeros
bool shouldFillFirstRow = false;
bool shouldFillFirstCol = false;
// Check if the first row has any zero element
for (int j = 0; j < n; ++j)
if (matrix[0][j] == 0) {
shouldFillFirstRow = true;
break;
}
// Check if the first column has any zero element
for (int i = 0; i < m; ++i)
if (matrix[i][0] == 0) {
shouldFillFirstCol = true;
break;
}
// Store the information in the first row and the first column.
for (int i = 1; i < m; ++i)
for (int j = 1; j < n; ++j)
if (matrix[i][j] == 0) {
matrix[i][0] = 0; // Mark the corresponding element in the first column as 0
matrix[0][j] = 0; // Mark the corresponding element in the first row as 0
}
// Fill 0s for the matrix except the first row and the first column.
for (int i = 1; i < m; ++i)
for (int j = 1; j < n; ++j)
if (matrix[i][0] == 0 || matrix[0][j] == 0)
matrix[i][j] = 0;
// Fill 0s for the first row if needed.
if (shouldFillFirstRow)
for (int j = 0; j < n; ++j)
matrix[0][j] = 0;
// Fill 0s for the first column if needed.
if (shouldFillFirstCol)
for (int i = 0; i < m; ++i)
matrix[i][0] = 0;
}
};
Algorithm Steps
- Get the number of rows
m
and columnsn
of the matrix. - Initialize two flags
shouldFillFirstRow
andshouldFillFirstCol
to check if the first row or column needs to be filled with zeros. - Check if the first row has any zero element and set
shouldFillFirstRow
accordingly. - Check if the first column has any zero element and set
shouldFillFirstCol
accordingly. - Traverse the matrix from
(1, 1)
to(m-1, n-1)
and mark the corresponding elements in the first row and column as 0 if the current element is 0. - Traverse the matrix again from
(1, 1)
to(m-1, n-1)
and set the current element to 0 if the corresponding element in the first row or column is 0. - If
shouldFillFirstRow
is true, fill the entire first row with zeros. - If
shouldFillFirstCol
is true, fill the entire first column with zeros.
Time Complexity and Space Complexity
Time Complexity: O(m * n), where m is the number of rows and n is the number of columns. The algorithm traverses the matrix three times.
Space Complexity: O(1), as the algorithm uses constant extra space to store the flags shouldFillFirstRow
and shouldFillFirstCol
. The matrix is modified in-place.