Seven interview problems on grids. The move: find the order hiding in the grid, then spend each step on it, by flattening, by a staircase, or by searching a value or a size.
You work on the back end of a payments app, a ride app and a pricing service. The seven problems on this street all give you a grid. The grid is not sorted like a list, but some order is hiding in it.
Finding that order is the whole job. Sometimes the rows chain into one long sorted line. Sometimes rows and columns each rise, and no line exists. Sometimes the grid is far too large to build.
| Problem | The order in the grid | The tool |
|---|---|---|
| Count negatives in a sorted grid | each row ends in a boundary, and the boundaries line up | a boundary per row, or a staircase |
| Weakest rows of a roster grid | each row is ones, then zeros | the first zero of each row |
| Search a sorted grid by rows | the rows chain into one sorted line | flatten, one search |
| Search a grid sorted both ways | rows and columns rise | a staircase from a corner |
| Maximum side of a square under the limit | a smaller square is never worse | search the side, check with prefix sums |
| Kth smallest price in a rate card | the count of cells at most x grows with x | search the price, count per row |
| Smallest range of the grid cost | a larger tolerance never blocks a route | search the tolerance, check by flood fill |
Read the last column. Every tool but one halves a range, and the staircase walks. That is the first thing to decide.
Exercise · Predict the output: Which cells are the positions?. The grid has 3 rows and 4 columns, and its rows chain into one sorted line. The code turns four flat positions into cells and prints their values. What does it print?
cols = 4
grid = [[2, 4, 6, 8], [10, 12, 14, 16], [18, 20, 22, 24]]
out = []
for p in [0, 4, 5, 11]:
out.append(str(grid[p // cols][p % cols]))
print(",".join(out))The move has two parts, and you make them before you write any code.
First, name the order. There are three kinds on this street.
Rows that chain form one sorted line of rows times columns positions. Rows and columns that each rise form a staircase. A count or a check that only grows with a value or a size is an answer to search.
Second, spend each step on a whole piece. A flat search halves the positions, and a staircase drops a whole row or column. A search on a value halves the range of values.
At every step, what is left of the grid or of the range still holds the answer. The step removes a whole row, a whole column or half the range.
For a grid of 500 rows and 500 columns, the tools differ in cost. A flat search takes 18 steps, because there are 250,000 positions. A staircase takes at most 999 steps. A search of every row takes 500 rows times 9 steps, which is 4,500.
Chained rows read as one sorted line: position p is the cell in row p // cols and column p % cols.
Exercise · Break it: The wrong corner. This checks whether a score is in a grid whose rows and columns both never fall. It starts at the top-left corner and moves right when the cell is smaller, and down when it is larger. Find an input where it gives the wrong answer.
def contains(scores, target):
r, c = 0, 0
while r < len(scores) and c < len(scores[0]):
v = scores[r][c]
if v == target:
return 1
if v < target:
c += 1
else:
r += 1
return 0The Academy lessons Real values and 2D and Search on the answer teach the staircase and the search over values. The first-true template teaches the loop. This street does not teach them again. It changes four things.
The index maths is yours. A flat position p is the cell in row p // cols and column p % cols. The divisor is the width of a row, not the number of rows. In a 3 by 4 grid, position 11 is row 2, column 3.
Not every grid search halves. A grid sorted along rows and columns cannot be read as one line. Row by row, the grid 1, 4 over 2, 5 reads 1, 4, 2, 5, which is not sorted.
The staircase costs rows plus columns minus 1 steps, and that is the right cost for it.
The grid may not exist. A rate card with 30,000 rows and 30,000 columns has 900,000,000 cells, and its cell in row i, column j is i times j. Do not build it.
Search the price, from 1 to 900,000,000, which takes 30 steps. At each step count the cells at most x: row i holds min(cols, x // i) of them. That is 30,000 rows times 30 steps, or 900,000 operations.
The answer can be a size or a tolerance. In the square problem, a side that fits means every smaller side fits, because no alert count is negative. The side runs from 1 to 300, which takes 9 steps.
In the grid cost problem, a larger tolerance never blocks a route. A tolerance up to 1,000,000 takes 20 steps, and each step is a flood fill over 10,000 tiles.
Exercise · Find the bug: Cells at most x. This counts the cells of a rate card, with rows 1 to rows and columns 1 to cols, whose price i * j is at most x. It is right when x is small and wrong for larger x. Which line is wrong?
def count_at_most(rows, cols, x):
total = 0
for i in range(1, rows + 1):
total += x // i
return totalCount the cells at most x in a rate card with min(cols, x // i). Without the cap, a row counts more cells than it has.
Solve them in this order. The first two find a boundary in each row. The next four use a flat search, a staircase, a size and a tolerance. The last searches a value in a card that is never built.
Before you code each problem, write two lines: the order you see in the grid, and what one step removes. If one step removes only a single cell, the order is not used yet.
Give each problem about 25 minutes. Spend the first five on the two lines, and draw a grid of three rows and four columns with your own numbers on paper.
Run your approach by hand on the drawing. For a staircase, mark the cell you start at and the row or column you drop at every step.
Four edge cases come back on almost every rung. The grid has one row or one column, the target lies outside the grid, a row has nothing to count, and a count passes 32 bits. Write one small test for each.
Checkpoint · Two dimensional and matrices
Q1/5 What is the first thing to do with a grid problem on this street?
Answer: B
The tool follows from the order. Chained rows flatten, rising rows and columns need a staircase, and a count or a check that grows is a search on a value or a size.
Q2/5 A grid has 3 rows and 4 columns, and its rows chain into one sorted line. Which cell is flat position 7?
Answer: C
The row is 7 // 4 = 1 and the column is 7 % 4 = 3. The divisor is the width of a row.
Q3/5 Why start the staircase at the top-right corner, not the top-left?
Answer: B
At the top-left both neighbours are larger, so a smaller target does not say which way to go. At the top-right the two neighbours lie on opposite sides of the value.
Q4/5 Why does the count of cells at most x in a rate card use min(cols, x // i)?
Answer: C
Without the cap, row 1 would count x cells, even when it has only cols. For rows = 3, cols = 3 and x = 9, the count would be 16 instead of 9.
Q5/5 Why can you search the side of a square with a binary search in the square problem?
Answer: C
The check turns from true to false once as the side grows. That order is what lets the search halve the range of sides.
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.