Count and map a cluster tree with message passing
I was asked this
No reports yet. Sign in to say where you were asked it.
A cluster of n machines is wired as a rooted tree (any number of children per node). Each machine knows only three things: its own id (a string such as "4"), its parent's id ("-1" for the root, which stands for the external client), and the ids of its children.
Machines have no shared memory and can talk only to their parent and children, through a provided API:
-
send(to_id, message)puts a message on the wire and returns immediately. It does not wait for an answer. -
receive(from_id, message)is called on a machine when a message arrives. You implement this.
Messages can arrive in any order, and one machine may be handling several requests at the same time. A message is a small dictionary; you choose its fields.
An external client sends a request to the root. Support two requests:
-
count: the client must eventually receive the total number of machines in the cluster. -
topology: the client must eventually receive the cluster's shape as a string. A leaf is written as its id. A node with children is written asid(c1,c2,...), with the children in the order the node lists them. There are no spaces.
Implement the logic each machine runs in receive, plus any state it keeps. You can't block or wait inside receive, and you can't read another machine's memory.
Example 1
0
/ \
1 2
/ \ / \
3 4 5 6
-
count→7 -
topology→"0(1(3,4),2(5,6))"
Example 2
The root is machine 2. Its children are 0 and 1, and 0 has one child, 3.
-
count→4 -
topology→"2(0(3),1)"
Constraints
-
1 <= n <= 10^5; the tree is connected and has exactly one root. - Message delivery is reliable but unordered (see the follow-ups for lost messages).
- A
countand atopologyrequest may be in flight at the same time.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to submit your code; every attempt is kept here.

