KatInterview

Find Tree K-th Ancestor for Queries

Trees & GraphsAuto-graded · 18 test cases
EasyAuto-gradedTrees & Graphstrees-graphsmath-bitsarrays

Last updated

Answer k-th ancestor queries on a rooted tree efficiently using binary lifting.

You are given a rooted tree containing $n$ nodes, numbered $1$ through $n$. The structure of the tree is defined by a 1-based parent array par, where:

  • par[i - 1] indicates the parent of node $i$.
  • If node $i$ is the root of the tree, par[i - 1] = -1.

You are also given a list of queries, where each query is represented as a pair [u, k]:

  • u is the starting node label ($1$-based).
  • k is a non-negative integer representing the number of parent steps to take upward.

For each query, begin at node u and climb up towards its parent k times. If you reach the root node before completing all k steps, remain at the root for any remaining steps.

Return a list of integers containing the final node label for each query in the order given.

Constraints

  • $0 \le n \le 2 \times 10^5$
  • $0 \le q \le 2 \times 10^5$, where $q$ is the number of queries.
  • For each query [u, k], $1 \le u \le n$ and $0 \le k \le 10^9$.
  • The input array par forms a valid tree with exactly one root and no cycles.

Examples

Example 1

Input: ancestor_walk_queries([-1, 1, 1, 2, 2, 2, 2], [[1, 0], [4, 1], [4, 2], [4, 5], [7, 1], [7, 3]])

Output: [1, 2, 1, 1, 2, 1]

Example 2

Input: ancestor_walk_queries([-1], [[1, 0], [1, 10]])

Output: [1, 1]

Example 3

Input: ancestor_walk_queries([-1, 1, 2, 3], [[4, 0], [4, 1], [4, 2], [4, 3], [4, 100]])

Output: [4, 3, 2, 1, 1]

Hints

Hint 1

Iterating upward step-by-step for each query takes O(k) per query, which will TLE when trees are deep and k is large.

Hint 2

Consider precomputing powers-of-two jumps (binary lifting) for each node.

Hint 3

If the root points to itself as its parent, steps beyond the root naturally stop at the root without needing extra boundary checks.