KatInterview

Find k-th Subordinate in Cascade Traversal

Trees & GraphsAuto-graded · 21 test cases
MediumAuto-gradedTrees & Graphstrees-graphsdfstree-traversal

Last 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] = -1 indicates that member i + 1 is the root leader of the entire organization.
  • Otherwise, parent[i] is the 1-based ID of the direct supervisor of member i + 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:

  1. Identify u's direct subordinates (children in the tree), sorted in ascending order of their 1-based IDs.
  2. Send the alert to the subordinate with the smallest ID first.
  3. 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$
  • parent forms 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.