Given an m × n integer matrix, if an element is 0, set its entire row and column to 0. You must do it in place.
matrix = [[1,1,1],[1,0,1],[1,1,1]][[1,0,1],[0,0,0],[1,0,1]]matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]][[0,0,0,0],[0,4,5,0],[0,3,1,0]]firstRowZero, firstColZeromat[r][c]==0 set mat[r][0]=0 and mat[0][c]=0mat[r][0]==0 or mat[0][c]==0 → set mat[r][c]=0firstRowZero, fix col 0 if firstColZeroWe repurpose the first row and first column as flag arrays — they already exist in the matrix, so no extra storage is needed. The only catch: before we overwrite them with markers, we must remember whether they themselves originally contained zeros (stored in firstRowZero and firstColZero). Then we mark, zero, and finally fix those edge rows/cols.
Zeroing rows and columns while you scan is wrong, because the new zeros would trigger more zeros. Copying the matrix fixes that, but costs O(m) times n space.
First record which rows and columns must become zero, then apply it. To use constant space, store those marks in the first row and the first column themselves. Two extra flags remember whether the first row and first column had a zero of their own.
Mark first, apply later, so new zeros do not spread. The first row and column can store the marks for free.
Run the animation above on your own input, or watch the 1:37 video explanation of Set Matrix Zeroes with a dry run and Java code.