Find k-th Subordinate in Cascade Traversal
Trees & GraphsAuto-graded · 21 test casesLast updated
Find the k-th node reached during a preorder depth-first traversal of a specific node's subtree when children are visited in ascending numerical order.
An organizational structure is represented as a rooted tree containing $n$ members labeled $1$ to $n$.
You are given a 0-indexed array parent of length $n$. The 1-based member ID corresponding to index i is i + 1. Specifically:
parent[i] = -1indicates that memberi + 1is the root leader of the entire organization.- Otherwise,
parent[i]is the 1-based ID of the direct supervisor of memberi + 1.
When member u (given as a 1-based ID) broadcasts an alert, it cascades through all of u's descendants (all members in the subtree rooted at u, excluding u itself) according to the following deterministic process:
- Identify
u's direct subordinates (children in the tree), sorted in ascending order of their 1-based IDs. - Send the alert to the subordinate with the smallest ID first.
- Before sending the alert to the next direct subordinate, the alert must completely finish propagating through the entire subtree of the current subordinate using the exact same propagation rules.
This propagation sequence defines a 1-indexed order of descendants, matching a depth-first search (DFS) preorder traversal of u's subtree (excluding u itself), where direct children are always visited in ascending order of their IDs.
Given the hierarchy parent, the initiator u (1-based ID), and a 1-based index k, determine the ID of the $k$-th descendant who receives the alert. If u has fewer than k descendants (or if $k < 1$), return -1.
Constraints
- $n = \text{len}(\text{parent})$
- $1 \le n \le 2 \times 10^5$
parentforms a valid rooted tree with exactly one root (parent[i] = -1).- For non-root nodes,
1 <= parent[i] <= n. - $1 \le u \le n$
- $1 \le k \le n$
Examples
Example 1
Input: kth_recipient([-1, 1, 1, 2, 2, 3], 1, 4)
Output: 3
Example 2
Input: kth_recipient([2, -1, 2, 1], 2, 2)
Output: 4
Example 3
Input: kth_recipient([-1, 1, 1], 2, 1)
Output: -1
Hints
Hint 1
The sequence of alert recipients corresponds to a preorder traversal of u's subtree, excluding u itself.
Hint 2
Subtree traversals form contiguous ranges of nodes. Calculate the total size of each node's subtree.
Hint 3
You can navigate down the tree by skipping whole child subtrees whose sizes are smaller than the remaining k value.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The cascade sequence follows a depth-first search (DFS) preorder traversal of the subtree rooted at u, visiting child nodes in ascending numerical ID order, excluding node u itself.
Instead of performing a full traversal for each query (which takes $O(n)$ time), we can leverage subtree sizes to jump over entire branches:
- Build adjacency lists of direct subordinates for each member, sorted in ascending order by member ID.
- Perform an explicit iterative DFS starting from the global root to obtain a full preorder sequence of nodes.
- Compute the size of each node's subtree in a bottom-up fashion by iterating over the preorder traversal in reverse.
- Verify if $k$ is within bounds ($1 \le k < \text{subtree_size}[u]$). If $k$ is out of bounds, return
-1. - Start at
node = uand inspect its sorted direct children:- If $k \le \text{subtree_size}[\text{child}]$, the target descendant lies within this child's subtree.
- If $k = 1$, the target descendant is the child itself.
- If $k > 1$, step into the child (
node = child), decrement $k$ by 1 (since the child occupies position 1 of its subtree block), and repeat. - If $k > \text{subtree_size}[\text{child}]$, subtract
subtree_size[child]from $k$ and examine the next sibling child.
Complexity
- Time Complexity: $O(n \log n)$ to construct and sort the adjacency lists, generate the global DFS order, and calculate subtree sizes. Finding the $k$-th node descends the tree depth, taking at most $O(n)$ operations.
- Space Complexity: $O(n)$ auxiliary space for adjacency lists, traversal ordering, tree stack, and subtree size arrays.
Reference Solution
from typing import List
def kth_recipient(parent: List[int], u: int, k: int) -> int:
n = len(parent)
children = [[] for _ in range(n + 1)]
root = -1
for person, manager in enumerate(parent, start=1):
if manager == -1:
root = person
else:
children[manager].append(person)
for reports in children:
reports.sort()
order = []
stack = [root]
while stack:
node = stack.pop()
order.append(node)
for child in reversed(children[node]):
stack.append(child)
subtree_size = [1] * (n + 1)
for node in reversed(order):
for child in children[node]:
subtree_size[node] += subtree_size[child]
if k < 1 or k >= subtree_size[u]:
return -1
node = u
while True:
for child in children[node]:
size = subtree_size[child]
if k <= size:
node = child
break
k -= size
else:
return -1
if k == 1:
return node
k -= 1