Find k-th recipient in command propagation order
ImcSoftware Engineer · Online AssessmentLast updated
This question evaluates understanding of tree traversals, subtree indexing, and order-statistics on rooted trees, focusing on DFS-preorder propagation when children are visited in ascending id.
Chain of Command (k-th Receiver in DFS-by-Child-Id Order)
A company org chart forms a rooted tree with n people (nodes), labeled 1..n.
You are given an array parent[1..n] describing the tree:
parent[i] = -1meansiis the root (top leader)- otherwise,
parent[i]is the direct manager (parent) of personi - each node has zero or more direct reports (children)
Command propagation rule
When a person u issues a command, it is sent to all subordinates of u (all descendants of u), using this strict order:
- Consider
u’s direct children, sorted by increasing person id. - Send the command to the smallest-id child first.
- Before sending to the next child, the command must be fully propagated throughout the current child’s entire subtree using the same rule.
This defines a deterministic traversal order over the descendants of u:
- It is equivalent to a DFS preorder over
u’s subtree excludingu, where children are visited in ascending id.
Task
Given:
parent[1..n]- an issuer
u - an integer
k(1-indexed)
Return the person id of the k-th subordinate who receives the command in the propagation order.
If u has fewer than k descendants, return -1.
Input/Output
- Input:
parent[],u,k - Output: the person id of the k-th recipient, or
-1
Notes / Assumptions
- The input forms a valid tree (exactly one root).
kis 1-indexed over recipients (descendants only; the issueruis not counted).- Constraints may be large (e.g.,
nup to 2e5), so an approach better than simulating propagation step-by-step for each query is typically expected (if multiple queries are present, state how many).
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.