Count a tree you can only message
- Turn a recursive count into two messages, an ask that goes down and an answer that comes back up, with a handler that returns nothing
- Keep each machine's state between messages: who asked it, and which children have answered, filed by child
- Finish only when every child has answered, whatever order the network delivers in, and build the tree's shape in the children's list order
- Survive lost and repeated messages: ask again on a timeout, answer a repeat from memory, and count a repeated answer once
- Run several counts at once by keeping every piece of state under a request id
- Answer the follow-ups: a machine that never answers, links that form a graph, the cost in messages and rounds, and the tests you would write
Count the machines in a tree
OpenAI software engineer candidates report a coding question about counting the machines in a tree (2 reports). In one write-up, from a technical screen (1 report), you get the root of the tree and one call that sends a message, and you write the handler that receives one. Our version of the first part reads like this:
Every node in this tree is its own machine. A machine knows its own id and its children's ids, and nothing else. The only way to reach another machine is
send(to_id, message), which returns at once. Some time later the network callsreceive(from_id, message)on the machine you sent it to. Messages can arrive in any order.Write the class
Machine. I callstart()on the root and deliver messages until none are left. Then the root'scountmust hold the number of machines in the tree.
Tree, as machine: its children Root root.count0: [1, 2],1: [3, 4]0 5 5: []5 1 7: [9, 3],9: [12, 5]7 5 0: [1],1: [2],2: [3]0 4
The reports give the root, the send call and the handler you write. The delivery order and these examples are ours. The later levels follow the write-up's follow-ups: the root also returns the shape of the whole tree, then the network loses and repeats messages so machines must ask again, then several counts run at once, each with its own request id.
You don't write it yet. The lesson starts with the count you would write on one machine, then cuts it into messages one idea at a time. At the end you solve the whole problem, level by level, in an interview simulation with a 60-minute timer.
This lesson builds on a tree walked by recursion, and on the seen-set from the hash maps lesson, which comes back when the links form a graph. Here each machine runs on its own, with no shared memory, and a message is the only way to reach another.
On one machine, the count is a recursion
If you could see the whole tree, you would count it with a recursion. A tree is a dict from each machine to the list of its children. The count under a machine is 1 for itself plus the count under each child.
# id -> children
TREE = {0: [1, 2], 1: [3, 4], 2: [], 3: [], 4: []}
def size(tree: dict[int, list[int]], node: int) -> int:
"""The number of machines under node, node included."""
return 1 + sum(size(tree, child) for child in tree[node])
print(size(TREE, 0), size(TREE, 1), size(TREE, 4))
5 3 1
Watch what each call does. It asks each child for a number, waits for all of them, adds 1 and hands the total back to whoever called it. The calls go down the tree and the totals come back up:
That is the whole protocol, before any network. The call going down becomes a message, an ask. The value coming back becomes another message, an answer. Everything after this handles what a network does to those two messages: it delays them, reorders them, loses them and repeats them.
One more number matters later: the depth of the tree, the links on the longest path from the root down to a machine with no children. Every ask has to travel down that path and every answer back up it, so the depth sets how long a count takes.
The editor holds TREE and the size above. Write depth(tree, node) by recursion: it takes the deepest child, never the sum of the children.
A message is a call cut in two
On one machine, a call waits for its answer. Across machines, nothing waits. send(to_id, message) puts the message in the network's queue and returns at once. Later, maybe much later, the network calls receive(from_id, message) on the other machine. That is the sendAsyncMessage and receiveMessage pair from the report.
Here is a machine that tells the time to whoever asks:
# (to, message) for each send
outbox = []
def record(to: int, message: tuple) -> None:
outbox.append((to, message))
class Clock:
"""Answers the time to whoever asks."""
def __init__(self, node_id: int, send) -> None:
self.node_id, self.send = node_id, send
def receive(self, from_id: int, message: tuple) -> None:
if message == ("time?",):
self.send(from_id, ("time", 12))
clock = Clock(8, record)
print(clock.receive(2, ("time?",)))
print(outbox)
None
[(2, ('time', 12))]
Two things changed from a call:
- The answer goes out through
send, addressed tofrom_id. A handler's return value goes nowhere, because the network callsreceiveand throws away what it returns. That is why the first line printsNone. - The machine learns who asked from
from_id. Nobody told it in advance.
record is a fake send. It writes each message down instead of delivering it. That's how you test one handler with no network at all: call receive yourself and read what it tried to send.
Each message here is a tuple whose first item names its kind: ("ask",) asks for a count, and ("answer", n) carries one. In an interview you can pick any format, as long as you say it out loud before you write the handlers. The tests here expect these two.
The editor holds Leaf, a machine with no children, and the same record. Write Leaf.receive: when an ask arrives, it sends an answer with its count, 1, back to the machine that asked.
The network picks the order
The tests own the network. It keeps a list of pending messages, each one (from, to, message). Each step, it takes one message out and calls receive on the machine it was sent to. That call can send more messages, which join the same list.
Which message comes out next is the network's choice. The tests try three rules:
- First in, first out (fifo): the oldest pending message.
- Last in, first out (lifo): the newest one.
- Shuffled: a random one, from a seeded random generator so a failure can be repeated.
Here are the eight messages of a count of the five-machine tree, in fifo order. Step through them:
In lifo order the same eight messages arrive in a different order. The root's ask to 2 was sent last, so it comes out first:
In last in, first out order, which message is delivered second?
Each machine remembers who asked, and who has answered
A recursive call keeps its state on the stack: who called it, and the totals so far. A machine has no stack across messages. Between one receive and the next, everything it knows has to live on self.
What does a machine need to remember?
- Its parent. The machine that asked it. It learns this from
from_idof the first ask, and it sends its answer there. - The answers so far, in a dict from child id to that child's count. A dict, not a running total, because later you'll need to know which children have answered.
Here is the five-machine tree partway through the last step's fifo run, after message 6:
When an ask arrives, a machine stores the asker as its parent and sends an ask to each child. A machine with no children has nobody to wait for, so it answers 1 at once. That is the base case of the recursion.
The editor holds Machine, with its state set up in __init__: self.parent and self.replies. Write the ask branch of receive: store the parent, ask each child in list order, and answer at once when there are no children.
Answer your parent once the last answer is in
When an answer arrives, file it under the child that sent it: self.replies[from_id] = count. Then check whether you're done. You're done when every child has answered, which is len(self.replies) == len(self.children). Then your answer is 1 for yourself plus the children's counts, sent to your parent.
Put that check in one method, finish_if_done, and call it from two places:
- after each answer arrives,
- right after the asks go out. A machine with no children is done at that moment, so the leaf case needs no code of its own.
def finish_if_done(replies: dict[int, int], children: list[int]) -> int | None:
"""The answer to send up, or None while a child still owes one."""
if len(replies) < len(children):
return None
return 1 + sum(replies.values())
print(finish_if_done({3: 1}, [3, 4]), finish_if_done({3: 1, 4: 1}, [3, 4]), finish_if_done({}, []))
None 3 1
A machine answers exactly once. Before the last answer it sends nothing. After it, it sends one answer.
The editor holds Machine with the ask side written as ask_children. Write the answer branch of receive, and write finish_if_done so the machine answers its parent once every child is in.
A count that only works in order
Here is a tempting shortcut. Children are asked in list order, so surely they answer in list order, and a machine is done when its last child answers?
Look at the lifo run again. Machine 1 asks 3 and then 4, and 4's answer arrives first. Under the shortcut, machine 1 sees its last child answer and sends its parent a count of 2, with 3 still missing. In fifo order on a small test, the bug hides.
Machine 0 has children [1, 2]. Machine 1 is a leaf. Machine 2 has one child, 3. In fifo order, does the root hear from 1 or from 2 first?
The root keeps the answer
The root is the one machine nobody asked. The test calls start() on it instead of sending an ask. start does what any machine does on an ask, with no parent: self.ask_children(parent=None).
The difference comes at the end. When the root is done, there's nobody to send the total to. So finish_if_done asks one question: is self.parent None? If it is, store the total in self.count. If not, send it to the parent.
Two cases to check before you call it done:
- A root with no children.
startasks nobody, andask_childrencallsfinish_if_doneat once, which setscountto 1 and sends nothing. If yourstartsends the asks without checking,countstaysNoneforever. - A root whose id isn't 0. Nothing in the code may assume the root's id. The parent being
Noneis what makes a machine the root.
The editor holds the whole level 1 Machine except two lines. Write start, and finish finish_if_done so the root stores self.count and every other machine sends its total to its parent.
File each answer by child, then read them in list order
Level 2 asks the root for the whole tree as a string: a machine's id, then its children's shapes in parentheses, in the order of its children list. A machine with no children is just its id. The five-machine tree is 0(1(3,4),2).
Each machine builds its own piece from its children's pieces, the same way it adds their counts. The trap is the order. Answers arrive in any order, and a dict keeps keys in the order they went in. So replies.values() gives the shapes in arrival order:
replies = {}
replies[4] = "4" # first
replies[3] = "3(9)"
print(",".join(replies.values()))
print(",".join(replies[child] for child in [3, 4]))
4,3(9)
3(9),4
The first line changes with the network. The second follows the list, so it's the same every time. File by child, then read in list order.
Machine 7 has children [9, 3]. Machine 3 answers first. What shape should 7 send up?
One answer carries the count and the shape
There's no need for a second round of messages. Put both values in the same answer: ("answer", count, shape). Each machine stores the pair under the child that sent it, and when every child is in, it builds both:
- the count is 1 plus the children's counts,
- the shape is its id plus the children's shapes in list order.
The root stores both, in self.count and self.tree. Everyone else sends both up.
This is a pattern worth naming. Anything you can compute for a machine from its own value and its children's results travels up in the same pass: a count, a sum, a maximum, the shape. The worked example later counts free disk the same way.
The editor holds the level 1 Machine, with self.tree added and two parts cut out. Write the answer branch of receive and the end of finish_if_done, so one answer carries the count and the shape.
Test a protocol against the one-machine answer
How do you know the protocol works? The hand-picked trees are a start. They can't show you every order a network might pick, or every tree shape. So write two helpers:
random_tree(n, seed): machines 0 to n - 1, where machine k gets a parent picked from the machines before it. Picking only earlier machines means every machine hangs off machine 0, and there can't be a cycle. A seededrandom.Randommakes every tree repeatable, so a failing seed can be rerun.shape(tree, node): the answer worked out on one machine, by the recursion from the first step. This is your oracle, the slow version you trust.
Then the test is a loop: for many seeds, build a tree, run the protocol in fifo, lifo and several shuffles, and compare the root's count and shape with the oracle's. A bug that depends on order or shape shows up within a few seeds.
In an interview, say this plan out loud once level 1 passes. It's the answer to "how would you test this?" before anyone asks it.
The editor holds random_tree and shape, both to write. Write them, and the tests check that the same seed gives the same tree.
A retry can deliver a message twice
Level 3 makes the network unreliable. The write-up's follow-up asks what happens when a machine crashes or a message fails, and suggests retries with a request id and cached answers, so nothing is counted twice (1 report).
Here is why retries bring repeats. A machine asks a child and waits. Nothing comes back for a while. Was the ask lost, or the answer, or is the child just slow? The machine can't tell. The only safe move is to ask again. If the child was only slow, it now gets the ask twice, and the parent may get two answers. Networks that retry deliver at least once, never exactly once.
So a repeat must change nothing. That property has a name, idempotent: doing it twice has the same effect as doing it once.
A dict of answers keyed by child is nearly idempotent. A second answer from 3 writes the same value under the same key, but it also runs finish_if_done again, and that sends a second answer up the tree. So ignore an answer from a child that's already in the dict: then a repeat changes nothing. A counter can't even tell the copies apart:
| After these answers | replies dict | counter waiting, total |
|---|---|---|
| 3: 1 | {3: 1}, waiting for 4 | 1 left, 2 |
| 3: 1 again | {3: 1}, waiting for 4 | 0 left, 3, so it answers |
| 4: 1 | {3: 1, 4: 1}, answers 3 | ignored |
The counter answers 3, which happens to be right here, but too early and for the wrong reason: it counted 3 twice and never heard from 4. On a deeper tree the numbers come out wrong.
The editor holds a level 1 Machine that keeps self.waiting and self.total instead of a dict. Run it to see machine 1 answer before 4 has said anything, then change how Machine keeps its answers so a repeat changes nothing.
A timeout asks again
Lost messages need a timer. In a real system, a machine that has waited too long for a child asks again. The tests stand in for the clock: when the network goes quiet and the root has no answer, they call tick() on every machine. A tick is a timeout firing.
On a tick, what should a machine do?
- Asked, and still waiting: send a new ask to each child that hasn't answered. Not to the children that have. They'd only answer again, and on a big tree that's a flood of messages for nothing.
- Never asked: nothing. It isn't part of a count yet.
- Already answered: nothing. Its part is done.
Two flags tell the three apart. self.asked turns on when the machine starts its part, and self.answer holds the answer it sent, once it has sent one. The next step uses self.answer again.
The editor holds the level 2 Machine, now with self.asked and self.answer, and an empty tick. Write tick: a machine that was asked and hasn't answered asks again each child missing from self.replies.
A finished machine answers again from memory
Now the other side. Machine 1 answered its parent, and the answer was lost. The parent's tick asks 1 again. What should 1 do?
It shouldn't ask its children again. They answered already, and asking them starts a second wave down the whole subtree. It already knows the answer, so it sends self.answer again. That's the cached answer from the write-up.
So an ask arriving at a machine has three cases:
| The machine | On an ask |
|---|---|
| has answered | send self.answer to the asker again |
| is still waiting | ignore it. Its own tick asks its children again |
| was never asked | store the parent and ask its children |
Machine 1 is still waiting for 3 when its parent asks it a second time. What should it send?
Every machine retries, not only the root
Why do all machines tick, and not only the root? Follow one loss. The ask from 1 to 3 is lost. 1 waits for 3. The root waits for 1.
If only the root retries, it asks 1 again. But 1 is still waiting, so it ignores the repeat, as the last step's table says. Nothing ever asks 3 again, and the count never finishes. The machine that knows what's missing is 1, so 1 must be the one that asks.
That's the general rule: the machine waiting on a link retries that link. Every machine has its own timer, and each covers the link below it.
Only the root ticks. The answer from 4 to 1 is lost. Does the count finish?
Keep each count's state under its request id
Level 4 lets the root start a new count while another is running: start(request_id). The write-up's answer for concurrency is to keep the state of each request apart, by request_id (1 report).
Look at the level 3 state: one parent, one replies, one answer. Two counts at once would write into the same fields. Machine 1 would mix count a's answers with count b's, and finish both with one set of numbers, or ignore b's ask as a repeat of a's.
The fix is mechanical. Every message carries the request id second: ("ask", id) and ("answer", id, count, shape). Every piece of state becomes a dict keyed by that id:
self.open[id]: the counts in progress here, each with its parent and its replies,self.answers[id]: the answers this machine has sent, kept for repeats,- on the root,
self.counts[id]andself.trees[id].
A count moves from open to answers when it finishes. tick asks again for every open count. Nothing else changes: each count runs exactly the level 3 protocol, as if it were alone.
open_counts = {"a": {"parent": 0, "replies": {3: (1, "3")}},
"b": {"parent": 0, "replies": {}}}
print([(rid, sorted(state["replies"])) for rid, state in open_counts.items()])
[('a', [3]), ('b', [])]
The editor holds the level 4 Machine with all its state keyed by request id, and an empty receive. Write receive: answer a repeated ask from self.answers, start a count on a new id, and file each answer under its own id in self.open.
A kept answer belongs to one count
Between counts, the tree can change. Level 4 lets new machines join: the test appends a child's id to a machine's children, and the next count must find it. Machines also leave or crash in real fleets, which is why anyone counts more than once.
This is where a cache that ignores the request id breaks. Suppose machine 1 keeps one answer, the last one it sent. Count a finishes with 1's subtree at 2 machines. Machine 8 joins under 1. Count b asks 1, and 1 sees a kept answer and sends it, still 2. Count b never reaches 8.
The kept answer is a fact about one count. Key it by the request id, so a new count finds nothing kept and asks its children. An old count's repeat still gets its own answer back.
The editor holds a level 4 Machine that keeps one answer in self.answer for every request. Run it to see count b get count a's numbers, then fix the cache so each answer is kept for its own request only.
A worked example: say it back, then name the messages
In the room, don't start typing. Start with three short moves.
1. Say the rules back, and ask what isn't said. "Each machine knows its children, not its parent. Messages arrive in any order." Then ask:
- Is it a tree, or can a machine have two parents?
- Can messages be lost or repeated?
- Is there a clock, or a timeout I can rely on?
- Does the root just need a number, or more?
Each answer is a later level in disguise. Asking shows you see them coming.
2. Write the two message kinds and the state on the board. An ask goes down, an answer comes up. Each machine keeps its parent and its answers by child. Five lines of notes, and the code almost writes itself.
3. Code the plain version, then add. Level 1 first, tested in two orders. Each follow-up is then a small change: a second value in the answer, a tick, a cache, a request id.
Here's that last point on a new question. The interviewer says: "Same tree. Now tell me the total free disk across the fleet, and which machine has the most." It's the same protocol. Each machine's answer becomes a tuple of three things computed from its own value and its children's answers:
| Part of the answer | Own value | Combined with the children by |
|---|---|---|
| machines | 1 | adding |
| total free GB | self.free_gb | adding |
| the most free, as (GB, id) | (self.free_gb, self.node_id) | max |
A pair compares its first item first, so max of (GB, id) pairs finds the most free disk and carries its id along. That works for any value that combines the same way from the bottom up.
The editor holds a level 1 Machine with free_gb, its own free disk, and an empty finish_if_done. Write finish_if_done so each answer carries the count, the total free disk and the pair for the most free.
Run every order before you say it works
Before you tell the interviewer it works, run it. A strong habit is one helper that runs every test tree in every order and lists what failed. Then each change you make gets checked against all of them in one call.
run(machine_class, tree, root, order) builds the machines, starts the root and delivers until the network is quiet. It returns the root machine. Compare its count with size(tree, root), the one-machine answer.
Why does this matter so much here? Because a bug in a message protocol is usually a bug about order. The last-child shortcut from earlier, sending its answer only once, passes in fifo order on the tree 0: [1, 2], 2: [3], and counts 3 in lifo. A tree checked in one order proves very little.
The editor holds failing_orders, to write, and size. Write failing_orders(machine_class, trees, orders): run every tree in every order with run, and list the (root, order) pairs whose count is wrong. The tests supply run, so call it inside failing_orders, not at the top of the file. The tests run it on a right Machine and on two broken ones.
What interviewers ask next
One write-up lists follow-ups after the count (1 report). Here they are, with the level that covers each:
- Print the whole tree's structure. That's level 2.
- A machine crashes or a message fails. Retries, a request id and cached answers, so nothing counts twice. That's level 3, and the next step covers a machine that never comes back.
- Concurrency. Keep each request's state apart by its id. That's level 4. With threads, add a lock around each machine's state: a
threading.Lockthat only one thread can hold at a time, so two messages never change the same machine at once. - Build
sendAsyncMessageyourself, and test it. The interviewer may send you back to code it.
Two more come up naturally with this question, though the reports don't list them: what if the links form a graph, and what a count costs.
Build the network yourself
The network has two jobs. send puts a message at the end of a queue and returns, without calling anything. A run loop takes the oldest message and calls receive on the machine it was sent to, until the queue is empty.
Add one guard. Two machines that always reply to each other never go quiet, so run stops after a limit and returns how many it delivered. A test that hangs teaches you nothing. A test that stops at 1,000 deliveries tells you something answers forever.
The editor holds Network, with send and run to write, and Echo, a machine that answers a ping with a pong, to try it on. Write send and run.
What if a machine never answers?
A machine that crashed for good never answers, however often you ask. Retries alone make the count wait forever. In a real fleet, a machine is down somewhere almost all the time.
So add a deadline. After some number of ticks, a waiting machine stops waiting and answers with what it has. It must also say what's missing, or the root reports a number that looks complete and isn't. Each answer now carries a list of machines that never answered, and each parent passes its children's lists up with its own:
Note what the root can't know: how many machines sit under a machine that's down. A missing machine counts as missing, never as 1.
The editor holds partial_answer(node_id, children, replies), where each reply is a child's count and its own missing list. Write it: the count so far, and the missing list in the order of children. It prints the root's answer from the figure.
What if the links form a graph?
Suppose machines are linked as neighbors, and links can form cycles. Machine 2 might be asked by 1 and then by 3. The tree protocol counts it twice, once under each asker. On a cycle it never stops: asks go round and round.
The fix is the seen-set of a graph search, spread over the machines. Each machine remembers whether it was asked before:
- First ask: visit. Store the asker as the parent and ask every neighbor except the parent.
- Any later ask: answer 0 at once. This machine is already counted under its first parent.
The 0 answer matters. The second asker is waiting for this machine like any other neighbor. Ignore the ask, and the asker waits forever.
The asks that were answered for real form a tree inside the graph, a spanning tree. The count runs over it, and the 0 answers are the extra links.
The editor holds a Machine whose neighbors replace children, with visit written and the ask branch of receive cut out. Write the ask branch: visit on the first ask, and answer 0 on every later one.
How many messages, and how long?
With nothing lost, the cost is exact. Every machine but the root gets one ask and sends one answer. So a count of n machines sends 2(n - 1) messages, whatever the shape.
Time is different. Say each message takes one round to arrive. The asks reach the bottom of the deepest path after depth rounds, and the answers need as many to come back. A count takes 2 × depth rounds.
| Tree of 100 machines | Messages | Rounds |
|---|---|---|
| a star, the root with 99 children | 198 | 2 |
| a chain, 99 links deep | 198 | 198 |
Same messages, about a hundred times slower. Two ways to say it when asked: the protocol is O(n) messages and O(depth) time. Retries add a timeout's wait each time a message is lost along the slowest path.
Depth bites code too. A recursive oracle on a chain of a thousand machines passes Python's default recursion limit of 1,000 calls. That's fine for the test trees, but worth saying before the interviewer asks.
The editor holds size and depth from the first step, and cost(tree, root) to write. Return the messages a count sends with nothing lost, and the rounds it takes.
What tests would you write?
When asked, name each test by the bug it catches. One tree per bug, small enough to check by hand:
- One machine. Catches a
startthat never checks whether it's already done. - A root whose id isn't 0. Catches code that assumes the root.
- Children listed out of sorted order, like
7: [9, 3]. Catches a shape that sorts. - Uneven branches, a leaf next to a deep branch. Catches finishing on the last child's answer, because the leaf answers long before its sibling.
Then the general checks from earlier: random trees in every order against the oracle, every message delivered twice, a lost message on each kind of link, and two counts at once.
The editor holds edge_trees(), to write, which returns a list of (tree, root) pairs. The tests run four broken machines on your trees in fifo and lifo order, and pass when each one fails on at least one tree.
1.Machine 1 has children [3, 4]. Its handler finishes when the last child in the list, 4, has answered. When does this go wrong?
2.The network delivers some messages twice. Which way of keeping a machine's answers stays right?
3.The answer from machine 1 to the root was lost, after 1 had finished. The root's tick asks 1 again. What should 1 do?
4.Only the root has a timer. The ask from machine 1 to its child 3 is lost. What happens?
5.Two counts, a and b, run at once. Machine 1 keeps one parent, one dict of answers and one kept answer. What goes wrong?
6.A tree of 1,000 machines is a single chain. With nothing lost, how many messages does a count send, and how many rounds does it take if each message takes one round?