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 vertex i.
  • Exactly one vertex root has par[root - 1] == -1, marking the root of the tree (note that root can be any label in 1..n, and parent labels may be either smaller or larger than child labels).
  • par is 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, where n = len(par)
  • 0 <= q <= 2 * 10^5, where q = len(queries)
  • par[root - 1] == -1 for a unique root in 1..n, and 1 <= par[i - 1] <= n for every i != root
  • par always forms a valid rooted tree with no cycles
  • Each query [u, k] satisfies 1 <= u <= n and 0 <= k <= 10^18

Step-by-step walkthrough

  1. Understand the parent array and stopping rule

    We are given a rooted tree with n nodes labeled 1..n and a list par of length n: - Because Python lists are 0-indexed while node labels start at 1, the parent of node node is stored at par[node - 1]. - Exactly one node has par[root - 1] == -1; that node is the root (note that the root is not guaranteed to be node 1, and a parent's label can be larger than its child's).

    Each query [u, k] starts at node u and climbs k parent 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 k steps does to depth: each step moves to the ancestor at depth 1 smaller, clamping at depth 0 (the root). So if u sits at depth d, the answer to [u, k] is always the ancestor of u at depth max(0, d - k)!

  2. 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 either k steps are used or -1 is 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 node
    

    This is great as a brute-force reference for tests, but each query takes min(k, depth(u)) hops. If 200,000 nodes form a vertical chain (1 <- 2 <- ... <- 200,000) and 200,000 queries ask to walk from node 200,000 with k = 200,000, total work reaches 4 * 10^10 hops—far too slow.

  3. 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_path of every node from the root down to our current node.

    Look at root_path the moment our search visits node 6 in 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 node is already sitting in root_path indexed by its exact depth! And because all queries are handed to us up front, we can process them offline: group queries by their start_node, visit every tree node once in DFS order, answer all queries waiting at node in O(1) each, and write each result into its original query index.

  4. Build child lists and bucket queries by start node

    The par array only points upward (child -> parent), whereas a top-down DFS needs downward edges (parent -> children). One pass over 1..n builds children[parent] and locates root at the same time. A second pass groups queries into queries_at[start_node] alongside each query's original index query_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))
    
  5. Maintain `root_path` iteratively without recursion

    Writing a recursive dfs(node) in Python crashes with RecursionError on a 200,000-node chain (Python's default call-stack limit is 1,000). Instead, we keep our own explicit stack dfs_stack of (node, depth) pairs.

    How do we keep root_path accurate when jumping from the bottom of one branch to the start of a sibling branch? Think about when (node, depth) was pushed onto dfs_stack: its parent (at depth - 1) had just placed itself at root_path[depth - 1] and pushed all its children at depth. Because a stack is last-in, first-out, everything popped before (node, depth) belonged to sibling subtrees at depths >= depth—meaning root_path[0 .. depth - 1] was never touched!

    So whenever we pop (node, depth), popping items off root_path while len(root_path) > depth trims the finished sibling branch right back to node's parent, and root_path.append(node) extends the path to node:

    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 n nodes is appended to root_path once, root_path.pop() can execute at most n times 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))
    
  6. Trace Example 1 step by step

    Let's trace par = [2, -1, 2, 1, 1, 4] with queries = [[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)] = 2
    

    Reading answers in index order 0..5 gives [4, 1, 2, 2, 1, 3], matching Example 1.

  7. 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). Scanning par to build children and locate root visits each of the n nodes once (O(n)). Bucketing queries visits each of the q queries once (O(q)). During the iterative DFS, each node is pushed and popped from dfs_stack once and appended and popped from root_path at most once (O(n) total), and each query performs one max plus one O(1) list index (O(q) total).
  • Space: O(n + q). children, dfs_stack, and root_path hold at most n node entries each (O(n)), while queries_at and answers store one entry per query (O(q)).

Edge cases

  • k = 0 (zero steps): max(0, depth - 0) equals depth, returning root_path[depth], which is the starting node u itself.
  • k >= depth (overshooting the root, including huge k like 10^18): depth - k <= 0 clamps cleanly to index 0 (root_path[0], the root) in O(1) time without looping k times.
  • Single-node tree (par = [-1]): root = 1 at depth 0, so every query [1, k] returns 1.
  • Root is not node 1, or parent labels exceed child labels: par = [2, 5, 5, -1, 4] has root 4; scanning for -1 and walking downward via children makes zero assumptions about label ordering.
  • Degenerate chain of 200,000 nodes: Explicit dfs_stack avoids recursion limits completely, and root_path answers every deep query in O(1).
  • Empty query list (queries = []) or duplicate queries: Empty queries returns [], and duplicate queries each carry their own query_idx in queries_at[u].

Common mistakes

  • Off-by-one indexing on par: Node labels run 1..n while Python lists run 0..n-1. Reading par[node] instead of par[node - 1] shifts every parent lookup and raises IndexError at node == n.
  • Assuming node 1 is always the root or par[i] < i: Nothing in the problem restricts label order; always locate the unique -1 entry to find root.
  • Using recursive DFS in Python: A valid tree can have depth n - 1 = 199,999, crashing Python's default recursion limit of 1,000.
  • Returning answers in DFS visit order instead of query order: Always pair each bucketed query with query_idx and assign answers[query_idx].
  • Walking upward k times per query: Clean on small tests, but O(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): Precompute up[j][v] = node reached after 2^j upward steps from v, setting up[0][root] = root so overshooting stays parked at the root, then clamp k = min(k, n - 1) and jump for each 1 bit of k. Slightly slower and uses O(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 timestamp tin[v] and append v to nodes_at_depth[depth[v]]. Because a subtree occupies a contiguous range of tin values, the ancestor of u at target_depth = max(0, depth[u] - k) is the last node in nodes_at_depth[target_depth] whose tin <= 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_path arrays simultaneously without O(n^2) space. Switch to either binary lifting (O(n log n) build, O(log n) query) with up[0][root] = root and k = min(k, n - 1), or the depth-list + tin binary 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 par contains -1 at exactly one index root and every other entry is an integer in 1..n. Then build children and run the same iterative DFS from root, counting visited nodes: in a graph with n nodes and n - 1 directed child edges, reaching all n nodes from root proves there are zero cycles and every node connects to root.
  • 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 v attaches under parent p, set depth[v] = depth[p] + 1, up[0][v] = p, and up[j][v] = up[j - 1][up[j - 1][v]] for j = 1 .. L - 1 in O(log max_n) time, since all of p's ancestors already exist.

Follow-up questions

Similar questions

More Others interview questions

All 4 Others questions →