We basically are required to iterate through the matrix at least twice:
- the first time is necessary to identify all the matrix values that have been set equal to
0
- you cannot change while iterating, as there is no way to differentiate between existing
0values and newly-converted0values- the second time is necessary to convert all the relevant matrix values to
0
Now, in the first iteration, I realised that if matrix[i][j] == 0,
we could simply convert:
- the value present in the first column (of the same row),
matrix[i][0] - the value present in the first row (of the same column),
matrix[0][j]
and then on our second iteration, we can check if either matrix[i][0] == 0 or matrix[0][j] == 0
to determine if matrix[i][j] should be converted to 0.
Unfortunately, there does exist the edge case of matrix[0][0]
as values on the first row and first column will end up converting it when equal to 0.
Therefore, we can initialize a boolean col0 to check whether we should convert column 0 to all 0s.
code
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
bool col0 = false;
for (int i = 0; i < matrix.size(); ++i) {
if (matrix[i][0] == 0) {
col0 = true;
}
for (int j = 1; j < matrix[0].size(); ++j) {
if (matrix[i][j] == 0) {
matrix[i][0] = matrix[0][j] = 0;
}
}
}
for (int i = matrix.size()-1; i >= 0; --i) {
for (int j = matrix[0].size()-1; j >= 1; --j) {
if (matrix[i][0] == 0 || matrix[0][j] == 0) {
matrix[i][j] = 0;
}
}
if (col0) {
matrix[i][0] = 0;
}
}
}
};
complexity
- Time:
O(n*m)wheren*mare the dimensions of the matrix- Space:
O(1)
time taken
- 9 minutes exactly