Find Tree K-th Ancestor for Queries
Trees & GraphsAuto-graded · 18 test casesLast 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]:
uis the starting node label ($1$-based).kis 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
parforms 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.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A direct traversal climbing up parent by parent takes $O(k)$ time per query. When $k$ is large or trees are skewed, this results in overall $O(q \cdot k)$ execution time, which exceeds time limits.
We can solve this problem using Binary Lifting:
-
Precomputation Table: We construct a jump table
up[j][i]which stores the node reached after taking $2^j$ steps upward from node $i$.- Base case ($j = 0$):
up[0][i]is simply the direct parent of node $i$. To handle steps beyond the root effortlessly, we assignup[0][root] = root(a self-loop). - Recurrence relation ($j > 0$):
up[j][i] = up[j - 1][up[j - 1][i]], because making a jump of size $2^j$ is equivalent to making two consecutive jumps of size $2^{j - 1}$.
- Base case ($j = 0$):
-
Answering Queries: To answer a query $(u, k)$, we represent $k$ in binary. For each set bit at position $b$ in $k$, we jump from the current node to its $2^b$-th ancestor.
Complexity
- Time Complexity:
- Table construction: $O(n \cdot \log(\max k))$
- Query evaluation: $O(q \cdot \log(\max k))$
- Overall Time Complexity: $O((n + q) \log(\max k))$, which takes well under a second for $n, q \le 2 \times 10^5$.
- Space Complexity: $O(n \cdot \log(\max k))$ to store the precomputation table.
Python Reference Solution
from typing import List
def ancestor_walk_queries(par: List[int], queries: List[List[int]]) -> List[int]:
n = len(par)
if n == 0:
return []
max_k = max((k for _, k in queries), default=0)
levels = max(1, max_k.bit_length())
# Convert node labels to zero-based indices and make the root its own parent.
first = [i if p == -1 else p - 1 for i, p in enumerate(par)]
up = [first]
for _ in range(1, levels):
prev = up[-1]
up.append([prev[prev[i]] for i in range(n)])
result = []
for u, k in queries:
node = u - 1
bit = 0
while k:
if k & 1:
node = up[bit][node]
k >>= 1
bit += 1
result.append(node + 1)
return result