K-th Ancestor Queries on a Tree

Medium · Coding & Algorithms · Software Engineer · Online Assessment

Problem Statement

A tree of n vertices labeled 0 through n - 1 has a single designated root. Its structure is given by an integer list parent of length n, where parent[v] is the direct parent of vertex v, and the root vertex is marked by parent[root] == -1. Note that the root does not have to be vertex 0, and a parent vertex may have either a smaller or a larger label than its children.

Build a query structure TreeAncestor that answers k-step upward jump queries:

  • TreeAncestor(n, parent) — preprocesses the n-vertex tree described by parent.
  • getKthAncestor(node, k) — starts at node and follows parent links upward k times, returning the vertex reached. When k == 0, zero edges are traversed and node itself is returned. If fewer than k ancestors exist above node (stepping upward passes the root), return -1.

The automated judge invokes your implementation through the driver function:

def tree_ancestor_queries(
    n: int,
    parent: List[int],
    operations: List[str],
    arguments: List[List[int]],
) -> List[Optional[int]]:

Each index i pairs operations[i] with arguments[i]: - "init" with [] constructs TreeAncestor(n, parent) and appends None to the output list. - "getKthAncestor" with [node, k] calls getKthAncestor(node, k) and appends the returned integer.

Examples

Example 1

Input:
  n = 8
  parent = [-1, 0, 0, 1, 1, 2, 4, 4]
  operations = ["init", "getKthAncestor", "getKthAncestor", "getKthAncestor", "getKthAncestor"]
  arguments = [[], [6, 1], [7, 3], [5, 2], [6, 4]]

Output:
  [None, 4, 0, 0, -1]

Walk-through: Vertex 0 is the root (parent[0] = -1), with children 1 and 2; vertex 1 has children 3 and 4; vertex 2 has child 5; and vertex 4 has children 6 and 7. - getKthAncestor(6, 1) moves one link up from 6 to 4. - getKthAncestor(7, 3) climbs 7 -> 4 -> 1 -> 0, landing on 0. - getKthAncestor(5, 2) climbs 5 -> 2 -> 0, landing on 0. - getKthAncestor(6, 4) climbs 6 -> 4 -> 1 -> 0 in three steps and has nowhere to go on the fourth step, returning -1.

Example 2

Input:
  n = 3
  parent = [2, 0, -1]
  operations = ["init", "getKthAncestor", "getKthAncestor", "getKthAncestor"]
  arguments = [[], [1, 0], [1, 2], [0, 2]]

Output:
  [None, 1, 2, -1]

Walk-through: Here vertex 2 is the root (parent[2] = -1), vertex 0 sits below 2, and vertex 1 sits below 0 (2 <- 0 <- 1). - getKthAncestor(1, 0) takes zero steps and returns 1. - getKthAncestor(1, 2) climbs 1 -> 0 -> 2, returning 2. - getKthAncestor(0, 2) reaches root 2 after one step and runs out of ancestors on the second step, returning -1.

Constraints

  • 1 <= n <= 10^5
  • parent has length n and describes a valid rooted tree on vertices 0 .. n - 1 with a single -1 entry.
  • 1 <= q <= 10^5, where q is the number of "getKthAncestor" calls (len(operations) == len(arguments) == q + 1, beginning with "init").
  • 0 <= node < n
  • 0 <= k <= n

Step-by-step walkthrough

  1. Understand the problem and judge format

    We are given an n-vertex rooted tree labeled 0 through n - 1 via an array parent, where parent[v] records the immediate parent of vertex v and parent[root] == -1 (note that the root can sit at any index, and parents can have larger labels than their children).

    We need to support getKthAncestor(node, k): - Starting at node, follow k parent links upward. - If k == 0, we traverse zero links and return node itself. - If climbing k links passes the root, return -1.

    Example 1 tree: n = 8, parent = [-1, 0, 0, 1, 1, 2, 4, 4]
    
    Depth 0:            0          (parent[0] = -1)
                       / \
    Depth 1:          1   2        (parent[1] = 0, parent[2] = 0)
                     / \   \
    Depth 2:        3   4   5      (parent[3..4] = 1, parent[5] = 2)
                       / \
    Depth 3:          6   7        (parent[6..7] = 4)
    
    getKthAncestor(6, 1) -> 4
    getKthAncestor(7, 3) -> 0   (7 -> 4 -> 1 -> 0)
    getKthAncestor(5, 2) -> 0   (5 -> 2 -> 0)
    getKthAncestor(6, 4) -> -1  (6 -> 4 -> 1 -> 0 -> past root!)
    

    The judge calls tree_ancestor_queries(n, parent, operations, arguments), where "init" constructs TreeAncestor(n, parent) (recording None in the output list) and each "getKthAncestor" passes [node, k] and records the returned integer.

  2. Start with one-step jumps (and why they time out)

    The direct simulation follows node = parent[node] k times, stopping early if node becomes -1:

    from typing import List
    
    
    def kth_ancestor_naive(parent: List[int], node: int, k: int) -> int:
        for _ in range(k):
            if node == -1:
                break
            node = parent[node]
        return node
    

    This is simple enough to serve as a test oracle, but each query takes O(k) steps. When all 10^5 nodes form a single chain (0 <- 1 <- ... <- 99,999) and 10^5 queries ask for deep ancestors (k near 10^5), total work hits 10^10 pointer hops—way too slow.

  3. Key idea: express `k` in binary to jump by powers of two

    Every non-negative integer k can be written uniquely as a sum of powers of two—its binary digits! For example, k = 13 in binary is 1101 (8 + 4 + 0 + 1):

    Instead of 13 single steps:
      v -> +1 -> +1 -> +1 -> +1 -> +1 -> +1 -> +1 -> +1 -> +1 -> +1 -> +1 -> +1 -> +1 -> target
    
    Jump once per '1' bit of 13 = 1 + 4 + 8 (only 3 lookups!):
      v  ---(+1 = 2^0)--->  a  ---(+4 = 2^2)--->  b  ---(+8 = 2^3)--->  target
    

    For n <= 10^5, any k < n has at most 17 binary digits (2^17 = 131,072 > 100,000). So if every node precomputes where a jump of 1, 2, 4, 8, ..., 2^16 steps lands, every query finishes in at most 17 array lookups! This technique is called binary lifting.

  4. Double the jump size with dynamic programming

    How do we precompute a jump of 2^level steps without walking 2^level times? Notice that climbing 2^level steps is the exact same thing as climbing 2^(level - 1) steps to a halfway node mid, and then climbing another 2^(level - 1) steps from mid!

    Jump of 2^level (e.g. 8 steps) = two jumps of 2^(level - 1) (4 steps + 4 steps):
    
       v  ------ 2^(level - 1) ------>  mid  ------ 2^(level - 1) ------>  target
                     |                                    |
             mid = up[level - 1][v]          target = up[level - 1][mid]
    

    This gives a clean recurrence: - Base row (level = 0, jump of 2^0 = 1): up[0][v] = parent[v]. - Next rows (level >= 1, jump of 2^level): mid = up[level - 1][v]. If mid == -1 (already past the root), then up[level][v] = -1; otherwise up[level][v] = up[level - 1][mid].

  5. Build the jump table safely level by level

    Before writing __init__, watch out for three classic traps:

    1. How many levels do we need? In an n-node tree, the deepest possible node has depth n - 1, so useful values of k are 0 .. n - 1. (n - 1).bit_length() gives the exact number of binary bit positions needed (wrapped in max(1, ...) so n = 1 still creates row 0).
    2. Loop order matters: Always put for level on the outside and for v on the inside. If you looped over v = 0 .. n - 1 on the outside and parent[0] = 5, node 0 would try to read up[level - 1][5] before node 5 was filled! Filling all nodes of level - 1 first guarantees prev_row[mid] is ready regardless of node numbering.
    3. Never index Python lists with -1: In Python, prev_row[-1] does not error—it silently returns the last element prev_row[n - 1]! Always check if mid != -1: before looking up prev_row[mid].

    Also note a practical Python layout choice: storing self.up[level][v] (~17 lists of length n) uses far less memory and builds much faster than up[v][level] (100,000 tiny lists).

    from typing import List
    
    
    class TreeAncestor:
        def __init__(self, n: int, parent: List[int]) -> None:
            self.n = n
            # Maximum depth in an n-node tree is n - 1, so we need enough binary bit positions
            # to represent 0 .. n - 1 (at least 1 level when n == 1).
            self.levels = max(1, (n - 1).bit_length())
    
            # up[level][v]: the (2**level)-th ancestor of node v, or -1 if climbing 2**level steps
            # goes past the root. Stored as [level][v] (~17 rows of size n) for compact memory.
            self.up: List[List[int]] = [list(parent)]
    
            # Outer loop MUST be over `level` so the entire `prev_row` is ready before reading
            # `prev_row[mid]`, even when `mid` has a larger node index than `v`.
            for level in range(1, self.levels):
                prev_row = self.up[level - 1]
                curr_row = [-1] * n
                for v in range(n):
                    mid = prev_row[v]
                    # Guard against mid == -1 because prev_row[-1] in Python reads the last element!
                    if mid != -1:
                        curr_row[v] = prev_row[mid]
                self.up.append(curr_row)
    
  6. Answer `getKthAncestor` bit by bit

    First check if k >= self.n: return -1. Why is this guard essential? - Logically, an n-node tree has at most n - 1 edges from bottom to root, so k >= n can never exist. - Technically, the constraints allow k == n. When n is a power of two (say n = 4), self.levels = (3).bit_length() = 2 (levels 0 and 1), while k = 4 is 0b100 (bit 2), which would read self.up[2] out of bounds without if k >= self.n!

    For 0 <= k < n, we inspect remaining bit by bit from lowest bit (level = 0) upward: - remaining & 1 is 1 when the current binary digit is 1, meaning our climb includes a jump of 2**level via self.up[level][current]. - remaining >>= 1 shifts all binary digits right by one place (integer division by 2), advancing to level + 1. - Stopping the while loop as soon as current == -1 avoids indexing self.up[level][-1].

    def getKthAncestor(self, node: int, k: int) -> int:
        if k >= self.n:
            return -1
    
        current = node
        remaining = k
        level = 0
    
        while remaining > 0 and current != -1:
            if remaining & 1:
                current = self.up[level][current]
            remaining >>= 1
            level += 1
    
        return current
    
  7. Trace Example 1 on the jump table

    For n = 8 and parent = [-1, 0, 0, 1, 1, 2, 4, 4], (8 - 1).bit_length() = (7).bit_length() = 3, so __init__ builds 3 rows (jumps of 1, 2, 4):

    Node v:             0   1   2   3   4   5   6   7
    -------------------------------------------------
    up[0] (+1 step):   -1   0   0   1   1   2   4   4
    up[1] (+2 steps):  -1  -1  -1   0   0   0   1   1
    up[2] (+4 steps):  -1  -1  -1  -1  -1  -1  -1  -1
    
    Query 1: getKthAncestor(6, 1)   [k = 1 = 0b001]
      level 0 (bit 1): current = up[0][6] = 4 -> remaining becomes 0 -> return 4
    
    Query 2: getKthAncestor(7, 3)   [k = 3 = 0b011]
      level 0 (bit 1): current = up[0][7] = 4
      level 1 (bit 1): current = up[1][4] = 0 -> remaining becomes 0 -> return 0
    
    Query 3: getKthAncestor(5, 2)   [k = 2 = 0b010]
      level 0 (bit 0): skip
      level 1 (bit 1): current = up[1][5] = 0 -> remaining becomes 0 -> return 0
    
    Query 4: getKthAncestor(6, 4)   [k = 4 = 0b100]
      level 0 (bit 0): skip
      level 1 (bit 0): skip
      level 2 (bit 1): current = up[2][6] = -1 -> loop finishes -> return -1
    

    Including None for "init", the full return list is [None, 4, 0, 0, -1].

  8. Complete solution

    Putting TreeAncestor and the judge driver tree_ancestor_queries together:

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    class TreeAncestor:
        def __init__(self, n: int, parent: List[int]) -> None:
            self.n = n
            # Maximum depth in an n-node tree is n - 1, so we need enough binary bit positions
            # to represent 0 .. n - 1 (at least 1 level when n == 1).
            self.levels = max(1, (n - 1).bit_length())
    
            # up[level][v]: the (2**level)-th ancestor of node v, or -1 if climbing 2**level steps
            # goes past the root. Stored as [level][v] (~17 rows of size n) for compact memory.
            self.up: List[List[int]] = [list(parent)]
    
            # Outer loop MUST be over `level` so the entire `prev_row` is ready before reading
            # `prev_row[mid]`, even when `mid` has a larger node index than `v`.
            for level in range(1, self.levels):
                prev_row = self.up[level - 1]
                curr_row = [-1] * n
                for v in range(n):
                    mid = prev_row[v]
                    # Guard against mid == -1 because prev_row[-1] in Python reads the last element!
                    if mid != -1:
                        curr_row[v] = prev_row[mid]
                self.up.append(curr_row)
    
        def getKthAncestor(self, node: int, k: int) -> int:
            # No node in an n-node tree has n or more ancestors; this also prevents indexing past
            # `self.levels - 1` when n is a power of two and k == n (e.g. n = 4, k = 0b100).
            if k >= self.n:
                return -1
    
            current = node
            remaining = k
            level = 0
    
            # Decompose `k` into powers of two from lowest bit to highest bit, stopping early at -1.
            while remaining > 0 and current != -1:
                if remaining & 1:
                    current = self.up[level][current]
                remaining >>= 1
                level += 1
    
            return current
    
    
    def tree_ancestor_queries(
        n: int,
        parent: List[int],
        operations: List[str],
        arguments: List[List[int]],
    ) -> List[Optional[int]]:
        results: List[Optional[int]] = []
        tree: Optional[TreeAncestor] = None
    
        # Replay each operation in sequence, returning None for `init` and int answers for queries.
        for op, args in zip(operations, arguments):
            if op == "init":
                tree = TreeAncestor(n, parent)
                results.append(None)
            else:
                node, k = args
                assert tree is not None
                results.append(tree.getKthAncestor(node, k))
    
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine climbing a 100,000-story tower where ordinary stairs only step up 1 floor at a time. Walking 50,000 floors per request is exhausting—unless every floor posts express-elevator links for power-of-two jumps: +1 floor, +2 floors, +4 floors, +8 floors, and so on. Because every whole number breaks into a sum of distinct powers of two (its binary digits—for instance, 13 = 8 + 4 + 1), you can reach any ancestor up to 100,000 steps away in at most 17 express jumps!

Why does the naive parent-pointer loop fail? Stepping node = parent[node] one link at a time takes O(k) work per query, so on a 100,000-node chain with 100,000 deep queries it executes roughly 10^10 steps and times out. Moreover, TreeAncestor must answer each getKthAncestor(node, k) call online as soon as it arrives, so we cannot batch all queries into a single offline pass.

We solve this with binary lifting (precomputing 2^level-step ancestor pointers at every node so any k-step climb takes O(log k) jumps), built via dynamic programming (computing larger subproblem answers directly from smaller already-computed ones): - Store up[level][v] = the (2^level)-th ancestor of v (or -1 if none exists). Row 0 is parent (2^0 = 1 step), and each next row uses the fact that two half-jumps of 2^(level - 1) make one jump of 2^level: up[level][v] = up[level - 1][up[level - 1][v]]. - To answer getKthAncestor(node, k), we read k's binary digits from lowest bit upward using a bitwise AND (remaining & 1, which tests whether the lowest bit is 1) and a right bit-shift (remaining >>= 1, which discards the lowest bit by dividing by 2), jumping via up[level][current] whenever a 1 bit appears.

Walk through a 5-node chain parent = [-1, 0, 1, 2, 3] (0 <- 1 <- 2 <- 3 <- 4): up[0] = [-1, 0, 1, 2, 3] (+1 step) and up[1] = [-1, -1, 0, 1, 2] (+2 steps). For getKthAncestor(4, 3), 3 in binary is 11 (1 + 2): bit 0 jumps 4 -> up[0][4] = 3, and bit 1 jumps 3 -> up[1][3] = 1, returning 1 in two lookups. For getKthAncestor(4, 5), k >= n (5 >= 5) immediately returns -1.

Complexity

Let n be the number of nodes, q be the number of getKthAncestor queries, and L = max(1, (n - 1).bit_length()) ≈ log2(n) (17 when n = 10^5).

  • Time — __init__: O(n log n). We fill L rows, and each row scans all n nodes once doing two O(1) list lookups per node (~1.7 * 10^6 operations for n = 10^5).
  • Time — getKthAncestor: O(log k) (at most O(log n)) per query, so O(q log n) across q queries. Any k >= n returns -1 in O(1), and any k < n shifts right once per bit of k (at most L <= 17 iterations), doing one O(1) array lookup per set bit.
  • Space: O(n log n). The 2D table self.up stores L lists of n integers each.

Edge cases

  • k = 0: The while remaining > 0 loop runs zero times and immediately returns node itself (even when node is the root).
  • k equals node depth vs. depth + 1: Climbing exactly depth steps lands on the root; climbing depth + 1 steps sets current = -1 and returns -1.
  • k = n (maximum allowed by 0 <= k <= n): No node in an n-node tree has n ancestors, and when n is a power of two (such as n = 4, k = 4 = 0b100), bit 2 exceeds the highest row index 1. Checking if k >= self.n: return -1 handles both cleanly.
  • Single-node tree (n = 1, parent = [-1]): (n - 1).bit_length() is 0, so max(1, ...) ensures self.levels = 1; k = 0 returns 0 and k = 1 returns -1.
  • Root not at 0, or parent[v] > v (e.g., parent = [1, 2, 3, -1]): Because self.up is populated row by row (level outer loop, v inner loop), prev_row[mid] is always ready regardless of node index order.
  • Line tree of 10^5 nodes: Worst case for step-by-step walking (10^5 steps/query), handled in at most 17 jumps per query here.

Common mistakes

  • Swapping the loop order in __init__ (for v outer, for level inner): Whenever a node's ancestor has a larger index than the node itself (parent = [1, 2, -1]), up[level][0] reads up[level - 1][1] before node 1 has been processed, leaving stale -1 entries.
  • Forgetting if mid != -1 or and current != -1 in Python: Negative list indexing in Python is valid (row[-1] reads the last element row[n - 1]), turning a missing ancestor -1 into an unrelated real node!
  • Allocating too few levels (e.g., int(math.log2(n))): For n = 9, int(math.log2(9)) is 3 (levels 0, 1, 2, max jump 4 + 2 + 1 = 7), which cannot represent k = 8 (0b1000, needs level 3). Using (n - 1).bit_length() gives 4 levels (0..3), covering every k <= 8.
  • Creating n lists of length L (up[v][level]) in Python: 100,000 separate Python list objects add substantial allocator overhead compared to 17 lists of length 100,000 (up[level][v]).

Alternative approaches

  • Depth lists + DFS entry timestamps (online, O(n) space, O(log n) query): Run an iterative DFS from the root to record each node's depth depth[v], entry timestamp tin[v], and per-depth list nodes_at_depth[d] (naturally sorted by tin). If k > depth[node], return -1; otherwise, binary search nodes_at_depth[depth[node] - k] for the rightmost node with tin <= tin[node]. Uses O(n) memory instead of O(n log n).
  • Skew-binary jump pointers (online, O(n) space, O(log n) query): Store just one extra jump pointer per node based on skew-binary numbers, achieving O(n) preprocessing and memory with O(log n) queries, though trickier to code under interview time pressure.

Follow-up questions

  • How much memory does the jump table require, and how can you reduce peak space usage to O(n)? Our binary lifting table stores L = ceil(log2(n)) rows of n integers, which takes O(n log n) space (~1.7 million integers for n = 10^5). As quick practical optimizations, you can cap levels at max_tree_depth.bit_length() (shrinking the table on shallow, wide trees) and store each row in Python's compact array('i') (4 bytes per integer instead of 28-byte Python int objects plus 8-byte list pointers). To cut asymptotic memory all the way down to O(n) while preserving O(log n) online queries, replace the jump table with DFS entry timestamps tin[v] plus per-depth sorted node lists and binary search, or heavy-light decomposition (splitting the tree into vertex-disjoint heavy chains so any root path crosses at most O(log n) chains).
  • Suppose edges can be re-assigned at runtime so a node moves under a different parent—how would you adapt your design? Re-attaching node x under new_parent alters the ancestors of x and every vertex inside x's subtree, while leaving vertices outside x's subtree intact. First verify new_parent does not lie inside x's subtree (which would introduce a cycle), then walk x's subtree top-down in breadth-first order and recompute up[0..L-1][u] for each subtree vertex u in O(subtree_size * log n) time. When large subtrees move frequently, replace the static table with a Link-Cut Tree (a self-adjusting forest of splay trees maintaining dynamic tree paths), which supports link, cut, and k-th ancestor lookups in O(log n) amortized time per operation.
  • How can the same power-of-two ancestor table compute the lowest common ancestor of any pair of nodes? The Lowest Common Ancestor (LCA) of a and b is the deepest vertex that is an ancestor of both. Precompute depth[v] for all vertices during initialization, then lift whichever vertex is deeper by abs(depth[a] - depth[b]) via getKthAncestor so both sit at the exact same depth; if a == b afterward, return a. Otherwise, scan level downward from self.levels - 1 to 0 and advance both a and b whenever up[level][a] != up[level][b], halting one step below the LCA so up[0][a] gives the answer in O(log n) time:

python def lca(self, a: int, b: int, depth: List[int]) -> int: if depth[a] < depth[b]: a, b = b, a a = self.getKthAncestor(a, depth[a] - depth[b]) if a == b: return a for level in range(self.levels - 1, -1, -1): if self.up[level][a] != self.up[level][b]: a = self.up[level][a] b = self.up[level][b] return self.up[0][a]

Follow-up questions

Similar questions

More Others interview questions

All 4 Others questions →