Upward K-Step Tree Queries with Root Clamping
Easy · Coding & Algorithms · Data Scientist · Online Assessment
Problem Statement
Implement ancestor_walk_queries(par, queries) to evaluate upward parent-climbing queries on a rooted tree.
The tree contains n vertices numbered 1 through n and is specified by a 0-indexed integer array par of length n:
- For each vertex
i(1 <= i <= n),par[i - 1]gives the immediate parent of vertexi. - Exactly one vertex
roothaspar[root - 1] == -1, marking the root of the tree (note thatrootcan be any label in1..n, and parent labels may be either smaller or larger than child labels). paris guaranteed to define a single connected, cycle-free rooted tree.
You are also given a list queries of q pairs [u, k], where u (1 <= u <= n) is the starting vertex label and k (k >= 0) is the requested number of upward parent hops. For each query, start at vertex u and step to the current vertex's parent k times. If the walk arrives at root before all k hops are spent, it remains parked at root for the remaining hops.
Return a list of q integers containing the final stopping vertex label for each query in input order.
Examples
Example 1
Input:
par = [2, -1, 2, 1, 1, 4]
queries = [[6, 1], [6, 2], [6, 3], [6, 8], [5, 1], [3, 0]]
Output:
[4, 1, 2, 2, 1, 3]
Explanation: Vertex 2 has par[1] = -1, so 2 is the root; 1 and 3 sit directly beneath 2, 4 and 5 sit beneath 1, and 6 sits beneath 4 (forming the chain 2 <- 1 <- 4 <- 6). Walking upward from 6 reaches 4 after 1 hop, 1 after 2 hops, and root 2 after 3 hops; asking for 8 hops stays clamped at root 2. One hop from 5 lands on 1, and 0 hops from 3 stays at 3.
Example 2
Input:
par = [3, 1, -1]
queries = [[2, 0], [2, 1], [2, 2], [2, 7]]
Output:
[2, 1, 3, 3]
Explanation: The tree is a three-vertex chain 3 <- 1 <- 2 rooted at 3. Starting at leaf 2, 0 hops stops at 2, 1 hop reaches 1, 2 hops reaches root 3, and 7 hops stays at 3.
Example 3
Input:
par = [2, -1]
queries = [[1, 1], [1, 4], [2, 5]]
Output:
[2, 2, 2]
Explanation: Vertex 2 is the root and vertex 1 is its child. Climbing 1 or 4 hops from 1 stops at 2, and starting directly at root 2 with 5 hops also stays at 2.
Constraints
1 <= n <= 2 * 10^5, wheren = len(par)0 <= q <= 2 * 10^5, whereq = len(queries)par[root - 1] == -1for a uniquerootin1..n, and1 <= par[i - 1] <= nfor everyi != rootparalways forms a valid rooted tree with no cycles- Each query
[u, k]satisfies1 <= u <= nand0 <= k <= 10^18
Step-by-step walkthrough
Understand the parent array and stopping rule
We are given a rooted tree with
nnodes labeled1..nand a listparof lengthn: - Because Python lists are0-indexed while node labels start at1, the parent of nodenodeis stored atpar[node - 1]. - Exactly one node haspar[root - 1] == -1; that node is the root (note that the root is not guaranteed to be node1, and a parent's label can be larger than its child's).Each query
[u, k]starts at nodeuand climbskparent links, staying parked at the root if it arrives there early. Let's sketch Example 1 (par = [2, -1, 2, 1, 1, 4]) with each node's depth (distance from the root):Depth 0: 2 (root: par[1] = -1) / \ Depth 1: 1 3 (par[0] = 2, par[2] = 2) / \ Depth 2: 4 5 (par[3] = 1, par[4] = 1) / Depth 3: 6 (par[5] = 4)Notice what climbing
ksteps does to depth: each step moves to the ancestor at depth1smaller, clamping at depth0(the root). So ifusits at depthd, the answer to[u, k]is always the ancestor ofuat depthmax(0, d - k)!Start with a step-by-step walk (and why it times out)
A direct simulation follows
par[node - 1]one step at a time until eitherksteps are used or-1is reached:from typing import List def walk_one_query(par: List[int], u: int, k: int) -> int: node = u steps = 0 while steps < k and par[node - 1] != -1: node = par[node - 1] steps += 1 return nodeThis is great as a brute-force reference for tests, but each query takes
min(k, depth(u))hops. If200,000nodes form a vertical chain (1 <- 2 <- ... <- 200,000) and200,000queries ask to walk from node200,000withk = 200,000, total work reaches4 * 10^10hops—far too slow.Key idea: answer queries offline during a tree walk
Suppose we walk the tree top-down from the root using depth-first search (DFS)—exploring down one branch as far as possible before backtracking to the next sibling branch—while maintaining a list
root_pathof every node from the root down to our current node.Look at
root_paththe moment our search visits node6in Example 1:Current node: 6 (depth = 3) root_path: [ 2, 1, 4, 6 ] Index/depth: 0 1 2 3 Query [6, 1] -> root_path[max(0, 3 - 1)] = root_path[2] = 4 Query [6, 2] -> root_path[max(0, 3 - 2)] = root_path[1] = 1 Query [6, 3] -> root_path[max(0, 3 - 3)] = root_path[0] = 2 Query [6, 8] -> root_path[max(0, 3 - 8)] = root_path[0] = 2 (clamped at root!)Every ancestor of
nodeis already sitting inroot_pathindexed by its exact depth! And because allqueriesare handed to us up front, we can process them offline: group queries by theirstart_node, visit every tree node once in DFS order, answer all queries waiting atnodeinO(1)each, and write each result into its original query index.Build child lists and bucket queries by start node
The
pararray only points upward (child -> parent), whereas a top-down DFS needs downward edges (parent -> children). One pass over1..nbuildschildren[parent]and locatesrootat the same time. A second pass groups queries intoqueries_at[start_node]alongside each query's original indexquery_idx:n = len(par) # children[v]: list of child node labels directly under node v (index 0 is unused for 1..n labels) children: List[List[int]] = [[] for _ in range(n + 1)] root = -1 for node in range(1, n + 1): # Node labels are 1..n, while `par` is a 0-indexed Python list. parent = par[node - 1] if parent == -1: root = node else: children[parent].append(node) # queries_at[u]: list of (steps, query_idx) for every query starting at node u queries_at: List[List[Tuple[int, int]]] = [[] for _ in range(n + 1)] for query_idx, (start_node, steps) in enumerate(queries): queries_at[start_node].append((steps, query_idx))Maintain `root_path` iteratively without recursion
Writing a recursive
dfs(node)in Python crashes withRecursionErroron a200,000-node chain (Python's default call-stack limit is1,000). Instead, we keep our own explicit stackdfs_stackof(node, depth)pairs.How do we keep
root_pathaccurate when jumping from the bottom of one branch to the start of a sibling branch? Think about when(node, depth)was pushed ontodfs_stack: its parent (atdepth - 1) had just placed itself atroot_path[depth - 1]and pushed all its children atdepth. Because a stack is last-in, first-out, everything popped before(node, depth)belonged to sibling subtrees at depths>= depth—meaningroot_path[0 .. depth - 1]was never touched!So whenever we pop
(node, depth), popping items offroot_pathwhilelen(root_path) > depthtrims the finished sibling branch right back tonode's parent, androot_path.append(node)extends the path tonode:Suppose a deep branch ended at depth 3: root_path is [2, 1, 4, 6] Next pop is an aunt branch (3, depth 1): while len(root_path) > 1: root_path.pop() -> pops 6, 4, 1 -> [2] root_path.append(3) -> [2, 3] (exact path to 3!)Because each of the
nnodes is appended toroot_pathonce,root_path.pop()can execute at mostntimes in total across the whole algorithm:answers = [0] * len(queries) # root_path[d]: ancestor at depth d on the path from root (depth 0) to the current node root_path: List[int] = [] # dfs_stack: explicit (node, depth) stack so deep chains up to 2e5 never hit RecursionError dfs_stack: List[Tuple[int, int]] = [(root, 0)] while dfs_stack: node, depth = dfs_stack.pop() # Any nodes explored after `node`'s parent pushed `node` belonged to sibling branches # at depth >= `depth`, so popping back to length `depth` leaves `node`'s exact ancestors. while len(root_path) > depth: root_path.pop() root_path.append(node) # Clamping depth - steps at 0 parks early arrivals at the root in O(1). for steps, query_idx in queries_at[node]: target_depth = max(0, depth - steps) answers[query_idx] = root_path[target_depth] for child in children[node]: dfs_stack.append((child, depth + 1))Trace Example 1 step by step
Let's trace
par = [2, -1, 2, 1, 1, 4]withqueries = [[6, 1], [6, 2], [6, 3], [6, 8], [5, 1], [3, 0]]:Popped (node, d) root_path after update Queries answered at this node ---------------- ------------------------ -------------------------------------------------- (2, 0) [2] (none) (3, 1) [2, 3] idx 5: [3, 0] -> root_path[max(0, 1-0)] = 3 (1, 1) [2, 1] (popped 3) (none) (5, 2) [2, 1, 5] idx 4: [5, 1] -> root_path[1] = 1 (4, 2) [2, 1, 4] (popped 5) (none) (6, 3) [2, 1, 4, 6] idx 0: [6, 1] -> root_path[2] = 4 idx 1: [6, 2] -> root_path[1] = 1 idx 2: [6, 3] -> root_path[0] = 2 idx 3: [6, 8] -> root_path[max(0, 3-8)] = 2Reading
answersin index order0..5gives[4, 1, 2, 2, 1, 3], matching Example 1.Complete solution
Here is the complete
O(n + q)solution:from typing import Any, Dict, List, Optional, Set, Tuple def ancestor_walk_queries(par: List[int], queries: List[List[int]]) -> List[int]: n = len(par) # children[v]: list of child node labels directly under node v (index 0 is unused for 1..n labels) children: List[List[int]] = [[] for _ in range(n + 1)] root = -1 for node in range(1, n + 1): # Node labels are 1..n, while `par` is a 0-indexed Python list. parent = par[node - 1] if parent == -1: root = node else: children[parent].append(node) # queries_at[u]: list of (steps, query_idx) for every query starting at node u queries_at: List[List[Tuple[int, int]]] = [[] for _ in range(n + 1)] for query_idx, (start_node, steps) in enumerate(queries): queries_at[start_node].append((steps, query_idx)) answers = [0] * len(queries) # root_path[d]: ancestor at depth d on the path from root (depth 0) to the current node root_path: List[int] = [] # dfs_stack: explicit (node, depth) stack so deep chains up to 2e5 never hit RecursionError dfs_stack: List[Tuple[int, int]] = [(root, 0)] while dfs_stack: node, depth = dfs_stack.pop() # Any nodes explored after `node`'s parent pushed `node` belonged to sibling branches # at depth >= `depth`, so popping back to length `depth` leaves `node`'s exact ancestors. while len(root_path) > depth: root_path.pop() root_path.append(node) # Clamping depth - steps at 0 parks early arrivals at the root in O(1). for steps, query_idx in queries_at[node]: target_depth = max(0, depth - steps) answers[query_idx] = root_path[target_depth] for child in children[node]: dfs_stack.append((child, depth + 1)) return answers✅ Submit now — all tests should pass.
Intuition & how it works
Imagine walking through a company org chart starting at the CEO (depth 0) down to every employee, carrying a clipboard that lists the exact chain of managers from the CEO down to the desk you are currently visiting—for example, [CEO, VP, Director, Engineer]. While you stand at that engineer's desk (depth 3), any question of the form "who do you reach if you climb k levels up, stopping at the CEO?" is just one glance at your clipboard: climbing 1 step reads index 3 - 1 = 2 (Director), climbing 2 steps reads index 3 - 2 = 1 (VP), and climbing 10 steps clamps to index max(0, 3 - 10) = 0 (CEO).
Why does the obvious simulation fail? Walking par one parent pointer at a time per query takes O(k) hops, so on a 200,000-node vertical chain with 200,000 deep queries it performs up to 4 * 10^10 hops and times out. Even if you use a tree walk, writing it with function recursion crashes on deep chains because Python stops nested calls at ~1,000 frames (RecursionError).
Because all queries are provided up front, we combine offline query processing (grouping queries in advance so we can answer them in whatever visit order suits our algorithm, then placing each result into its original index) with an iterative depth-first search (DFS) (exploring all the way down one branch before backtracking to the next sibling branch) driven by an explicit stack (a last-in, first-out list):
1. Invert par into downward children[v] lists and group queries into queries_at[u].
2. Push (root, 0) onto dfs_stack and maintain root_path, where root_path[d] holds the ancestor at depth d (distance in edges from the root).
3. Whenever (node, depth) is popped, trim any finished sibling suffix from root_path back to length depth, append node, and answer every (steps, query_idx) at node via root_path[max(0, depth - steps)].
Walk through a tiny 4-node example with par = [-1, 1, 2, 2] (1 is root; 2 is under 1; 3 and 4 are under 2) and queries [[3, 1], [4, 5]]. Visiting 1 sets root_path = [1]; visiting 2 sets root_path = [1, 2]; visiting 4 (depth 2) sets root_path = [1, 2, 4] and answers [4, 5] as root_path[max(0, 2 - 5)] = root_path[0] = 1; backtracking to sibling 3 (depth 2) pops 4, appends 3 to get root_path = [1, 2, 3], and answers [3, 1] as root_path[2 - 1] = 2.
Complexity
Let n be the number of nodes in par and q be the number of queries.
- Time:
O(n + q). Scanningparto buildchildrenand locaterootvisits each of thennodes once (O(n)). Bucketing queries visits each of theqqueries once (O(q)). During the iterative DFS, each node is pushed and popped fromdfs_stackonce and appended and popped fromroot_pathat most once (O(n)total), and each query performs onemaxplus oneO(1)list index (O(q)total). - Space:
O(n + q).children,dfs_stack, androot_pathhold at mostnnode entries each (O(n)), whilequeries_atandanswersstore one entry per query (O(q)).
Edge cases
k = 0(zero steps):max(0, depth - 0)equalsdepth, returningroot_path[depth], which is the starting nodeuitself.k >= depth(overshooting the root, including hugeklike10^18):depth - k <= 0clamps cleanly to index0(root_path[0], the root) inO(1)time without loopingktimes.- Single-node tree (
par = [-1]):root = 1at depth0, so every query[1, k]returns1. - Root is not node
1, or parent labels exceed child labels:par = [2, 5, 5, -1, 4]has root4; scanning for-1and walking downward viachildrenmakes zero assumptions about label ordering. - Degenerate chain of
200,000nodes: Explicitdfs_stackavoids recursion limits completely, androot_pathanswers every deep query inO(1). - Empty query list (
queries = []) or duplicate queries: Emptyqueriesreturns[], and duplicate queries each carry their ownquery_idxinqueries_at[u].
Common mistakes
- Off-by-one indexing on
par: Node labels run1..nwhile Python lists run0..n-1. Readingpar[node]instead ofpar[node - 1]shifts every parent lookup and raisesIndexErroratnode == n. - Assuming node
1is always the root orpar[i] < i: Nothing in the problem restricts label order; always locate the unique-1entry to findroot. - Using recursive DFS in Python: A valid tree can have depth
n - 1 = 199,999, crashing Python's default recursion limit of1,000. - Returning answers in DFS visit order instead of query order: Always pair each bucketed query with
query_idxand assignanswers[query_idx]. - Walking upward
ktimes per query: Clean on small tests, butO(n * q)worst-case time on deep trees.
Alternative approaches
- Binary lifting (online,
O(n log n)preprocessing and space,O(log n)per query): Precomputeup[j][v]= node reached after2^jupward steps fromv, settingup[0][root] = rootso overshooting stays parked at the root, then clampk = min(k, n - 1)and jump for each1bit ofk. Slightly slower and usesO(n log n)memory, but works even when queries arrive one by one online. - Depth lists with DFS entry timestamps (online,
O(n)preprocessing and space,O(log n)per query): Record each node's DFS entry timestamptin[v]and appendvtonodes_at_depth[depth[v]]. Because a subtree occupies a contiguous range oftinvalues, the ancestor ofuattarget_depth = max(0, depth[u] - k)is the last node innodes_at_depth[target_depth]whosetin <= tin[u], found via binary search (bisect_right).
Follow-up questions
- How would your solution change if each query had to be answered online before the next query arrived? Offline DFS cannot keep all nodes'
root_patharrays simultaneously withoutO(n^2)space. Switch to either binary lifting (O(n log n)build,O(log n)query) withup[0][root] = rootandk = min(k, n - 1), or the depth-list +tinbinary search approach (O(n)build and memory,O(log n)query). - How could you validate in linear time that the input parent array forms a single cycle-free rooted tree? First check that
parcontains-1at exactly one indexrootand every other entry is an integer in1..n. Then buildchildrenand run the same iterative DFS fromroot, counting visited nodes: in a graph withnnodes andn - 1directed child edges, reaching allnnodes fromrootproves there are zero cycles and every node connects toroot. - How would you support interleaved operations that attach new leaf vertices to existing tree nodes between queries? Binary lifting handles leaf insertions naturally without rebuilding the tree: when leaf
vattaches under parentp, setdepth[v] = depth[p] + 1,up[0][v] = p, andup[j][v] = up[j - 1][up[j - 1][v]]forj = 1 .. L - 1inO(log max_n)time, since all ofp's ancestors already exist.
Follow-up questions
- How would your solution change if each query had to be answered online before the next query arrived?
- How could you validate in linear time that the input parent array forms a single cycle-free rooted tree?
- How would you support interleaved operations that attach new leaf vertices to existing tree nodes between queries?
Similar questions
- K-th Ancestor Queries on a Tree
- Quarterly and Annual Transaction Breakdown by Coin
- Quarterly 2023 Revenue Query and Largest-File Shell Script
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses