A straightforward 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?
Solutions
Solution 1: Array Mark
Thinking
Zeroing a whole row and column as soon as we see a \(0\) wipes zeros we have not scanned yet, and we cannot tell original zeros from new ones. Copying an \(O(mn)\) matrix works, but the follow-up rejects that space. \(m,n \le 200\), so two scans are fine.
Record which rows and columns must be zeroed, then rewrite. An \(m\)-length row mark and an \(n\)-length column mark suffice: first pass only flags, second pass writes zeros. Extra space drops from \(O(mn)\) to \(O(m+n)\), still not the constant-space follow-up.
We use arrays rows and cols to mark the rows and columns to be cleared.
Then traverse the matrix again, and clear the elements in the rows and columns marked in rows and cols.
The time complexity is \(O(m\times n)\), and the space complexity is \(O(m+n)\). Where \(m\) and \(n\) are the number of rows and columns of the matrix respectively.
/** Do not return anything, modify matrix in-place instead. */functionsetZeroes(matrix:number[][]):void{constm=matrix.length;constn=matrix[0].length;constrow:boolean[]=Array(m).fill(false);constcol:boolean[]=Array(n).fill(false);for(leti=0;i<m;++i){for(letj=0;j<n;++j){if(matrix[i][j]===0){row[i]=col[j]=true;}}}for(leti=0;i<m;++i){for(letj=0;j<n;++j){if(row[i]||col[j]){matrix[i][j]=0;}}}}
Method 1 still spends \(O(m+n)\) on mark arrays. The follow-up wants \(O(1)\) extra space, and the first row and first column can play the role of \(\textit{row}\) and \(\textit{col}\). Those strips are both data and marks, so we save with \(i0\), \(j0\) whether they themselves must be zeroed, update the interior, and only then clear the first row and column — otherwise the marks get overwritten too early.
In the first method, we use an additional array to mark the rows and columns to be cleared. In fact, we can also use the first row and first column of the matrix to mark them, without creating an additional array.
Since the first row and the first column are used to mark, their values may change due to the mark, so we need additional variables \(i0\), \(j0\) to mark whether the first row and the first column need to be cleared.
The time complexity is \(O(m\times n)\), and the space complexity is \(O(1)\). Where \(m\) and \(n\) are the number of rows and columns of the matrix respectively.
/** Do not return anything, modify matrix in-place instead. */functionsetZeroes(matrix:number[][]):void{constm=matrix.length;constn=matrix[0].length;consti0=matrix[0].includes(0);constj0=matrix.map(row=>row[0]).includes(0);for(leti=1;i<m;++i){for(letj=1;j<n;++j){if(matrix[i][j]===0){matrix[i][0]=0;matrix[0][j]=0;}}}for(leti=1;i<m;++i){for(letj=1;j<n;++j){if(matrix[i][0]===0||matrix[0][j]===0){matrix[i][j]=0;}}}if(i0){matrix[0].fill(0);}if(j0){for(leti=0;i<m;++i){matrix[i][0]=0;}}}