Find k-th recipient in command propagation order
Company: Imc
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Take-home Project
Quick Answer: 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.
Constraints
- 1 <= n <= 2 * 10^5 (n = len(parent))
- People are labeled 1..n; parent is 0-indexed so parent[i] describes person i+1.
- Exactly one entry of parent equals -1 (the unique root).
- 1 <= u <= n
- 1 <= k, and the input forms a valid tree (no cycles).
- If u has fewer than k descendants, return -1.
Examples
Input: ([-1, 1, 1, 2, 2, 3], 1, 3)
Expected Output: 5
Explanation: children[1]=[2,3], children[2]=[4,5], children[3]=[6]. DFS preorder from root 1 (excluding 1): 2,4,5,3,6. The 3rd recipient is 5.
Input: ([-1, 1, 1, 2, 2, 3], 1, 1)
Expected Output: 2
Explanation: The first recipient is the smallest-id child of the root, which is 2.
Input: ([-1, 1, 1, 2, 2, 3], 2, 1)
Expected Output: 4
Explanation: Issuer u=2 has children [4,5]; the first recipient is 4.
Input: ([-1, 1, 1, 2, 2, 3], 2, 3)
Expected Output: -1
Explanation: Issuer u=2 has only 2 descendants (4 and 5), fewer than k=3, so return -1.
Input: ([-1, 1, 1, 2, 2, 3], 6, 1)
Expected Output: -1
Explanation: Person 6 is a leaf with no descendants, so any k returns -1.
Input: ([-1], 1, 1)
Expected Output: -1
Explanation: Single-node tree: the root has no subordinates, so return -1.
Input: ([-1, 1, 2, 3, 4], 1, 4)
Expected Output: 5
Explanation: A degenerate chain 1->2->3->4->5. DFS from 1: 2,3,4,5. The 4th recipient is 5.
Input: ([2, 3, -1, 3], 3, 2)
Expected Output: 1
Explanation: person1's parent=2, person2's parent=3, person3 is root, person4's parent=3. children[3]=[2,4], children[2]=[1]. DFS from 3: 2,1,4. The 2nd recipient is 1, showing ids are not assumed to be in traversal order.
Hints
- Build a children adjacency list from parent, then sort each node's children by id so the smallest-id child is visited first.
- The propagation order is exactly a DFS preorder of u's subtree with u itself excluded — count nodes as you pop them and stop when the count reaches k.
- Use an explicit stack and push children in reverse id order so the smallest id is processed next; this avoids recursion-depth limits for chains up to 2*10^5 deep.