Eight classic interview problems on trees, grids and dependency graphs, in our own wording. Spot the graph in the statement, pick the walk, and keep it iterative.
Trees and graphs fill a large share of coding interviews, and they rarely say so. The story talks about an org chart, a floor plan of racks or a list of build steps. Your first job is to see the graph inside it.
This set collects eight classic problems that the launch districts do not cover yet. Each one is our own version of a well-known interview problem, so you can practise the classics without memorising someone else's wording.
Interviewers stress three things with these problems.
A grid is the easiest graph to miss. Every cell is a node, and its neighbours up, right, down and left are its edges. Counting blocks of rack cells means counting the separate pieces of that graph, which needs a real walk, not a local rule.
Exercise · Break it: Counting blocks by their corners. This counts the blocks of rack cells (#) on a floor plan. It counts a cell as the start of a new block when the cells above it and to its left are not racks. Find a floor plan where it gives the wrong count.
def count_blocks(floor):
count = 0
for r, row in enumerate(floor):
for c, cell in enumerate(row):
up = r > 0 and floor[r - 1][c] == "#"
left = c > 0 and row[c - 1] == "#"
if cell == "#" and not up and not left:
count += 1
return countEach problem gives itself away with a signal in the statement. Here are the signals of the eight problems, with the move and the Academy lesson that teaches it.
| Signal in the statement | The move | Academy lesson |
|---|---|---|
| the number of levels; two trees the same | depth-first walk with a stack | Trees and binary search trees, Tree recursion |
| separate blocks of cells | flood fill from each unseen cell | BFS and DFS on a grid |
| steps that need other steps first | topological sort, with a heap for the smallest ready step | Topological sort |
| rows of a tree, level by level | breadth-first walk, one row per queue length | Trees and binary search trees |
| every node in its right place | carry lower and upper bounds down the walk | Trees and binary search trees |
| a path that spells a word | backtracking: mark, try the neighbours, unmark | Backtracking with pruning |
| the cheapest route with a limit | shortest paths over the state (hub, stops) | Dijkstra's shortest paths |
The Academy lessons teach each walk on its own. This set mixes them, so the skill you practise is choosing. Read the statement, find the signal, and name the walk before you write a line.
All the trees here are stored as arrays: left[i] and right[i] are the children of node i, and -1 means none. A chain of 100,000 nodes is allowed, so every walk uses its own stack or queue instead of recursion.
Exercise · Predict the output: Which order does the stack visit?. This walks a tree of six nodes with an explicit stack. It pushes the right child before the left child. What does it print?
values = [5, 3, 8, 1, 4, 9]
left = [1, 3, -1, -1, -1, -1]
right = [2, 4, 5, -1, -1, -1]
stack = [0]
order = []
while stack:
node = stack.pop()
order.append(values[node])
if right[node] != -1:
stack.append(right[node])
if left[node] != -1:
stack.append(left[node])
print(" ".join(map(str, order)))An explicit stack walks a tree depth-first: push the right child before the left, so the left side is visited first.
The other common failure is an edge read the wrong way round. In "step 1 needs step 0", the edge runs from 0 to 1: step 0 must finish first, and step 1 waits for it.
Exercise · Find the bug: The step that waits for the wrong one. This says whether every step can finish. A row [step, required] means step cannot start until required has finished. It runs the ready steps and counts them. Which line is wrong?
def can_finish(n, needs):
waiting = [0] * n
after = [[] for _ in range(n)]
for step, required in needs:
after[required].append(step)
waiting[required] += 1
ready = [v for v in range(n) if waiting[v] == 0]
done = 0
while ready:
v = ready.pop()
done += 1
for nxt in after[v]:
waiting[nxt] -= 1
if waiting[nxt] == 0:
ready.append(nxt)
return done == nIn step needs required, the edge runs from required to step; counting the wait on the wrong end leaves nothing ready.
The first four are easy and use one walk each. The last four are medium, and each adds one twist to a walk you already know. The minutes are time boxes for practice, close to what an interview allows.
Three of the twists are worth knowing before you start.
A search tree is valid only when each node fits the bounds of all its ancestors, not only its parent. A word path must free each cell on the way back, so another path can use it. And a route with a stop limit needs the number of stops in its state. The same hub reached with fewer stops can still lead to a cheaper trip.
In an interview, say the model out loud first: "the nodes are the people, and each edge points from a manager to a person who reports to them". It shows the interviewer your thinking, and it catches a wrong direction early.
The eight time boxes add up to 160 minutes. Split them into two sittings: the four easy problems take 65 minutes, and the four medium ones take 95.
If you finish a problem early, use the rest of its box well. Explain the walk aloud in one minute, as you would at the end of an interview, and say its cost in time and memory.
Checkpoint · Trees and graphs
Q1/5 A floor plan marks rack cells with #. What are the nodes and the edges of its graph?
Answer: B
A grid is a graph of cells. Neighbouring rack cells are joined, so a block of racks is one connected piece.
Q2/5 You must return the ids of a tree, row by row from the top. Which walk fits?
Answer: B
A queue visits the tree level by level. The queue's length at the start of a row tells you how many nodes that row holds.
Q3/5 Why do the walks in this set use their own stack or queue instead of recursion?
Answer: B
The depth of the recursion equals the height of the tree. A chain of 100,000 nodes is too deep for the default call stack of many languages.
Q4/5 A row [step, required] says that step waits for required. Which way does the edge point?
Answer: A
The step that waits gets the incoming edge, and its waiting count goes up. Read the other way round, nothing ever becomes ready.
Q5/5 Why is it not enough to compare each node of a search tree with its parent only?
Answer: B
A value can be right for its parent and still sit on the wrong side of the root. Carry lower and upper bounds down the walk instead.
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.