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.