Set Matrix Zeroes
1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
If a cell is 0, set its whole row and column to 0, in place.
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1Why can't you set zeros while scanning?
- Hint 2Record the rows and columns to clear in two sets.
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
A classroom seating chart where a zero means a student has a fever. The whole row and column near them are sent home. If you send people home while still reading the chart, you might send away people who were only near someone you just sent home. So first walk through the chart and list the feverish students' rows and columns. Then, in a second pass, clear those rows and columns.
- The obvious way
Copy the matrix and write zeros into the copy: O(rows x columns) extra space.
- The key insight
Pass 1: for each cell equal to 0 add its row to zero_rows and its column to zero_columns. Pass 2: for each cell, if its row or column is in those sets, set it to 0. (An O(1) space version stores the markers inside the first row and column.)
- The algorithm
- Two empty sets: zero_rows, zero_columns.
- Scan: note the row and column of every 0.
- Scan again: if the row or column is noted, set 0.
- Nothing to return (in place).
Watch it run
Examplematrix = [[1,1,1],[1,0,1],[1,1,1]]
First pass: the only zero is in the middle: note row 1 and column 1.
rows {1}, columns {1}Where people slip
- Do not zero while scanning; you would spread zeros much further than the question wants.
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
def set_zeroes(matrix):
rows, columns = len(matrix), len(matrix[0])
zero_rows, zero_columns = set(), set()
for row in range(rows):
for column in range(columns):
if matrix[row][column] == 0:
zero_rows.add(row) # first pass: only note, do not change
zero_columns.add(column)
for row in range(rows):
for column in range(columns):
if row in zero_rows or column in zero_columns:
matrix[row][column] = 0 # second pass: clearNow close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.