Another popular interview question is, zero the columns and rows which contain element value equal to zero.The trick here and question should be clear that,
- you should not lose the columns where zero is present while erasing the rows
- If either rows or columns is containing zero value, both of these rows & columns must be set to zero
If the above problems in zeroing is clear, then the solution is almost visible. We just need to create an bool array to hold whether the zero is present at some index of row and some index of column.
Just record the location where zero is present in row bool array and column where zero present in column bool array.
After finding this, we can simple zero the row’s where flag is set and columns where the flag is set.
- Since we can zero the rows after recording the column zero’s, we have started zeroing early. But its not necessary
- Instead of zero'ing column and rows seperately, we can zero both in one shot, using another for(i = 0->M) & for (j = 0->N) loop. We need to zero elements if either rows_bool[i] is true or columns_bool[j] is true.
- The above code is easily digestible and guessable at first run. But takes more or almost equal time if the above N2 loop is done