Reference: LeetCode
Difficulty: Medium
My Post: Java Solutions Extra Space + No Extra Space
Problem
Given a
m x nmatrix, if an element is0s, set its entire row and column to0. Do it in-place.
Example:
1  | Input:  | 
Follow up:
- 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 
O(1)space solution? 
Analysis
Extra Space
Use two sets rows and cols to record which row and column should be set to zeroes.
1  | public void setZeroes(int[][] matrix) {  | 
Time: $O(MN)$
Space: $O(M + N)$
Brute-Force + O(1) Space
We need two passes. The first pass is to set relevant non-zeroes to MODIFIED. The second pass is to set MODIFIED to 0.
Note: This value should not be in the matrix already; otherwise, this method won’t work.
1  | private final static int MODIFIED = -1000000;  | 
Time: $O(MN \times (M + N))$
Space: $O(1)$
Bette + O(1) Space
![]()
1  | public void setZeroes(int[][] matrix) {  | 
Time: $O(MN)$
Space: $O(1)$