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?
Solution:
fr = first row, fc = first col
Use first row and first column as markers. If matrix[i][j] = 0, mark respected row and col marker = 0 indicating that later this respective row and col must be marked 0; And because you are altering first row and column, we need to have two variables to track their own status.
For example, if any one of the first row is 0, fr = 0, at the end need to set all first row to 0;
classSolution: defsetZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ row0, col0 = 1, 1 for i in range(len(matrix)): for j in range(len(matrix[0])): ifnot matrix[i][j]: if i == 0: row0 = 0 if j == 0: col0 = 0 matrix[i][0] = 0 matrix[0][j] = 0 # Notice this starts from 1 because we use first row/col to store for i in range(1, len(matrix)): for j in range(1, len(matrix[0])): ifnot matrix[i][0] ornot matrix[0][j]: matrix[i][j] = 0 ifnot row0: for j in range(len(matrix[0])): matrix[0][j] = 0 ifnot col0: for i in range(len(matrix)): matrix[i][0] = 0 ```