← Questions

Count and map a cluster tree with message passing

0
OpenAISnowflakeCodingLast asked Sep 2026

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:

  1. count: the client must eventually receive the total number of machines in the cluster.
  2. 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 as id(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 count and a topology request may be in flight at the same time.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding