[LeetCode] Set Matrix Zeroes (Java)


Follow up:

Did you use extra space?
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?


Using $O(mn)$ and $O(m + n)$ space to implement it is easy. Just check the zeros and save their positions.

Since we need to do it in place, we can take full advantage of the matrix to save the useful information. We can use the first row and the first column to save whether there is a zero in such row or column. But we need to be careful that it’s possible that there is no zero in the first row or first column. When you change some entry in the first row to zero, you may not be able to know whether there is zero in this row or not. So we need to check it first.

And then we can check other entry. If it’s zero, for example, if matrix[i][j] is zero, we can update matrix[i][0] and matrix[0][j] to zero. After checking all entries, we can update the matrix according the the first row and the first column. If there is a zero, it means that we need to update all row or all column to zero.

Finally, we need to update the first row or first column. What we need is the checking information we mentioned above. According to them, we can decide it’s correct or not to update the first row or first column.



The time complexity is $O(mn)$. But the space complexity is constant.