Zero Matrix
1.8 Zero Matrix: Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0.
Brute force here is an obvious solution. My approach is to first scan through the matrix and collecting the indicies into two different arrays [i][j] where it is zero. These arrays I would then sort in nlogn time in order to remove duplicates.
e.g.
This would require me to also remove match indices, which seems needlessly complicated.
Instead, I'll go with another approach: scan through the matrix, by row. If I come across a zero, Ill break - there is no need to scan the remainder of that row. And then I emit everything in that row = 0.
I will have a column array, that I keep track of the columns that needed to be zero's out along the way. This column, I would then sort, and remove duplicates. Finally, I'd zero out the columns.
Last updated