Eight interview problems on grids of cells. The move: give every cell the address its question groups by, then visit by address and edit only after every reader is done.
You work on a warehouse system, a cinema booking app, an ad dashboard, a build system and a ride-hailing app. The problems on this street come from all five. Each one gives you a grid of cells, and the question groups the cells in some way.
The grouping changes from problem to problem. Here is each problem and the address that the grouping uses.
| Problem | The cells are grouped by | The address of cell (r, c) |
|---|---|---|
| Set rows and columns to zero | the row and the column of a zero | r, and c |
| Spiral order of a seating chart | the ring they sit on | the ring and the side |
| Rotate a tile image | where they land after a turn | (c, n - 1 - r) |
| Check a finished sudoku | row, column and block | r, c and the block number |
| Diagonals of a score grid | the diagonal they sit on | r + c |
| Free blocks across a wrapping day | the block of free cells they touch | the four neighbours, with the column taken modulo the width |
| Fares inside a price band | the fares at most a limit in each row | a pointer that only moves left, one step for each row |
| Game of life after one step | their eight neighbours | the cells around (r, c) |
Read the last column. A cell is never found by searching. You compute where it is, or where it goes.
The problems also differ in what they change. Some only read the grid, some build a new one, and some must edit the grid in place.
Write the address first, as a formula in r and c. Then decide the order in which the addresses are visited, and what each visit may change.
Every cell is visited through a computed address, once. A cell is overwritten only after every cell that needs its old value has read it.
The diagonal is the clearest address. The cells on one diagonal share the value r + c. A grid of 3 rows and 4 columns has 3 + 4 - 1 = 6 diagonals.
The report walks them in turn and alternates the direction. Even diagonals go up, from the lowest row to the highest, and odd ones go down.
Exercise · Predict the output: Which cells come second and fourth?. The code walks the diagonals of a grid with 3 rows and 4 columns. Even diagonals run from the lowest row up, and odd ones from the highest row down. What does it print?
grid = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
rows = len(grid)
cols = len(grid[0])
order = []
for d in range(rows + cols - 1):
cells = []
for r in range(rows):
c = d - r
if 0 <= c < cols:
cells.append(grid[r][c])
if d % 2 == 0:
cells.reverse()
order.extend(cells)
print(order[1], order[3])A block of a sudoku is an address of the same kind, and a small slip in its formula passes every simple test.
Exercise · Find the bug: Two blocks, one number. This checks that no label repeats inside any block of an n by n wall, where blocks are s by s. It is right for the top row of blocks but wrong below it. Which line is wrong?
def blocks_valid(grid, s):
seen = set()
for r in range(len(grid)):
for c in range(len(grid)):
v = grid[r][c]
if v == 0:
continue
block = (r // s) + (c // s)
key = block * 100 + v
if key in seen:
return False
seen.add(key)
return TrueCells on one diagonal share r plus c. Even diagonals are read upwards and odd diagonals downwards.
The Academy lesson Traversal and in-place edits shows grid loops and edits in place. Arrays in memory explains the layout of rows, and Keys, collisions and pitfalls covers keys that clash. This street changes four things.
Edits cascade. If you zero a row and column the moment you see a zero, the zeros you write are read later as if they were original. On the grid 1 0 1 / 1 1 1 / 1 1 1 the right answer zeroes row 0 and column 1 only. The in-place version zeroes all nine cells.
Old and new share a cell. In the game of life every cell changes at the same moment. Updating cells one by one makes later cells read new states.
A blinker is three live cells in a column of a 3 by 3 grid, and it turns into a row of three live cells. The one-by-one update gives all zeros.
Store a code such as 2 for "alive, will die" and 3 for "dead, will live". A neighbour reads the old state by treating 1 and 2 as alive, and the new state is read at the end.
Turns are modular. A quarter turn is a transpose, then each row reversed. A user who turns a 300 by 300 map 100,000 times would cause 9,000,000,000 cell moves, but 100,000 turns equal 0 turns modulo 4. At most 3 turns are ever needed, which is 270,000 moves.
Boundaries need guards. A spiral reads the top side, the right side, the bottom side and the left side of a ring, then shrinks the ring. When one row remains, the bottom side reads the same cells as the top side, and a single column does the same with the left side.
With one row left, the top side reads every cell. Check that rows remain before the bottom side.
Exercise · Break it: One row left. This reads a grid in a spiral: the top side, the right side, the bottom side, the left side, then it shrinks the ring. Find an input where it reads a cell twice.
def spiral_order(seats):
top, bottom = 0, len(seats) - 1
left, right = 0, len(seats[0]) - 1
out = []
while top <= bottom and left <= right:
for c in range(left, right + 1):
out.append(seats[top][c])
top += 1
for r in range(top, bottom + 1):
out.append(seats[r][right])
right -= 1
for c in range(right, left - 1, -1):
out.append(seats[bottom][c])
bottom -= 1
for r in range(bottom, top - 1, -1):
out.append(seats[r][left])
left += 1
return outAll eight problems share a level. The order goes from the idea you can state in one line to the one that needs the most care.
Before you code each problem, write two lines: the address of cell (r, c), and the order in which you visit the addresses. If the grid changes in place, add a third line: which cells still need the old value.
Give each problem about 25 minutes. Spend the first four on the address lines, and draw a 3 by 3 and a 1 by 3 grid with the addresses written in the cells. Then run your idea on the drawing before you code.
Three edge cases come back on most rungs. The grid can be a single row, a single column, or a single cell. Write one small test for each, and a fourth for a grid that is not square.
When a solution fails, check the address formula first. Most wrong answers on this street have one of three causes. They are a missing stride, a missing guard at a boundary, or an edit read before it is finished.
Checkpoint · Matrix and grid walks
Q1/5 Which value do all cells on one diagonal of a grid share?
Answer: C
Moving one step right and one step down-left keeps r + c the same. A grid with 3 rows and 4 columns has 3 + 4 - 1 = 6 diagonals.
Q2/5 A sudoku-style wall has blocks of s by s cells. Which formula numbers the block of cell (r, c)?
Answer: C
The row part needs the stride s. With the sum of the two parts alone, the blocks at row 0, column 2 and at row 2, column 0 of a 4 by 4 wall both get the number 1.
Q3/5 You zero each row and column the moment you see a zero, in the same grid. What goes wrong?
Answer: C
On 1 0 1 / 1 1 1 / 1 1 1 the right answer zeroes row 0 and column 1. The in-place version zeroes all nine cells.
Q4/5 A map is turned 100,000 times by a quarter turn. How many real turns do you need to make?
Answer: C
Four quarter turns bring the grid back. Turns only matter modulo 4, so at most 3 turns are ever needed.
Q5/5 When a spiral has one row left, why must the bottom side be guarded?
Answer: B
For the row 1, 2, 3 an unguarded loop returns 1, 2, 3, 2, 1. Check that rows remain before the bottom side, and columns before the left side.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.