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 then-vertex tree described byparent.getKthAncestor(node, k)— starts atnodeand follows parent links upwardktimes, returning the vertex reached. Whenk == 0, zero edges are traversed andnodeitself is returned. If fewer thankancestors exist abovenode(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^5parenthas lengthnand describes a valid rooted tree on vertices0 .. n - 1with a single-1entry.1 <= q <= 10^5, whereqis the number of"getKthAncestor"calls (len(operations) == len(arguments) == q + 1, beginning with"init").0 <= node < n0 <= k <= n
Step-by-step walkthrough
Understand the problem and judge format
We are given an
n-vertex rooted tree labeled0throughn - 1via an arrayparent, whereparent[v]records the immediate parent of vertexvandparent[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 atnode, followkparent links upward. - Ifk == 0, we traverse zero links and returnnodeitself. - If climbingklinks 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"constructsTreeAncestor(n, parent)(recordingNonein the output list) and each"getKthAncestor"passes[node, k]and records the returned integer.Start with one-step jumps (and why they time out)
The direct simulation follows
node = parent[node]ktimes, stopping early ifnodebecomes-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 nodeThis is simple enough to serve as a test oracle, but each query takes
O(k)steps. When all10^5nodes form a single chain (0 <- 1 <- ... <- 99,999) and10^5queries ask for deep ancestors (knear10^5), total work hits10^10pointer hops—way too slow.Key idea: express `k` in binary to jump by powers of two
Every non-negative integer
kcan be written uniquely as a sum of powers of two—its binary digits! For example,k = 13in binary is1101(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)---> targetFor
n <= 10^5, anyk < nhas at most17binary digits (2^17 = 131,072 > 100,000). So if every node precomputes where a jump of1, 2, 4, 8, ..., 2^16steps lands, every query finishes in at most17array lookups! This technique is called binary lifting.Double the jump size with dynamic programming
How do we precompute a jump of
2^levelsteps without walking2^leveltimes? Notice that climbing2^levelsteps is the exact same thing as climbing2^(level - 1)steps to a halfway nodemid, and then climbing another2^(level - 1)steps frommid!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 of2^0 = 1):up[0][v] = parent[v]. - Next rows (level >= 1, jump of2^level):mid = up[level - 1][v]. Ifmid == -1(already past the root), thenup[level][v] = -1; otherwiseup[level][v] = up[level - 1][mid].Build the jump table safely level by level
Before writing
__init__, watch out for three classic traps:- How many levels do we need? In an
n-node tree, the deepest possible node has depthn - 1, so useful values ofkare0 .. n - 1.(n - 1).bit_length()gives the exact number of binary bit positions needed (wrapped inmax(1, ...)son = 1still creates row0). - Loop order matters: Always put
for levelon the outside andfor von the inside. If you looped overv = 0 .. n - 1on the outside andparent[0] = 5, node0would try to readup[level - 1][5]before node5was filled! Filling all nodes oflevel - 1first guaranteesprev_row[mid]is ready regardless of node numbering. - Never index Python lists with
-1: In Python,prev_row[-1]does not error—it silently returns the last elementprev_row[n - 1]! Always checkif mid != -1:before looking upprev_row[mid].
Also note a practical Python layout choice: storing
self.up[level][v](~17lists of lengthn) uses far less memory and builds much faster thanup[v][level](100,000tiny 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)- How many levels do we need? In an
Answer `getKthAncestor` bit by bit
First check
if k >= self.n: return -1. Why is this guard essential? - Logically, ann-node tree has at mostn - 1edges from bottom to root, sok >= ncan never exist. - Technically, the constraints allowk == n. Whennis a power of two (sayn = 4),self.levels = (3).bit_length() = 2(levels0and1), whilek = 4is0b100(bit2), which would readself.up[2]out of bounds withoutif k >= self.n!For
0 <= k < n, we inspectremainingbit by bit from lowest bit (level = 0) upward: -remaining & 1is1when the current binary digit is1, meaning our climb includes a jump of2**levelviaself.up[level][current]. -remaining >>= 1shifts all binary digits right by one place (integer division by2), advancing tolevel + 1. - Stopping thewhileloop as soon ascurrent == -1avoids indexingself.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 currentTrace Example 1 on the jump table
For
n = 8andparent = [-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 -1Including
Nonefor"init", the full return list is[None, 4, 0, 0, -1].Complete solution
Putting
TreeAncestorand the judge drivertree_ancestor_queriestogether: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 fillLrows, and each row scans allnnodes once doing twoO(1)list lookups per node (~1.7 * 10^6operations forn = 10^5). - Time —
getKthAncestor:O(log k)(at mostO(log n)) per query, soO(q log n)acrossqqueries. Anyk >= nreturns-1inO(1), and anyk < nshifts right once per bit ofk(at mostL <= 17iterations), doing oneO(1)array lookup per set bit. - Space:
O(n log n). The 2D tableself.upstoresLlists ofnintegers each.
Edge cases
k = 0: Thewhile remaining > 0loop runs zero times and immediately returnsnodeitself (even whennodeis the root).kequals node depth vs.depth + 1: Climbing exactlydepthsteps lands on the root; climbingdepth + 1steps setscurrent = -1and returns-1.k = n(maximum allowed by0 <= k <= n): No node in ann-node tree hasnancestors, and whennis a power of two (such asn = 4, k = 4 = 0b100), bit2exceeds the highest row index1. Checkingif k >= self.n: return -1handles both cleanly.- Single-node tree (
n = 1, parent = [-1]):(n - 1).bit_length()is0, somax(1, ...)ensuresself.levels = 1;k = 0returns0andk = 1returns-1. - Root not at
0, orparent[v] > v(e.g.,parent = [1, 2, 3, -1]): Becauseself.upis populated row by row (levelouter loop,vinner loop),prev_row[mid]is always ready regardless of node index order. - Line tree of
10^5nodes: Worst case for step-by-step walking (10^5steps/query), handled in at most17jumps per query here.
Common mistakes
- Swapping the loop order in
__init__(for vouter,for levelinner): Whenever a node's ancestor has a larger index than the node itself (parent = [1, 2, -1]),up[level][0]readsup[level - 1][1]before node1has been processed, leaving stale-1entries. - Forgetting
if mid != -1orand current != -1in Python: Negative list indexing in Python is valid (row[-1]reads the last elementrow[n - 1]), turning a missing ancestor-1into an unrelated real node! - Allocating too few levels (e.g.,
int(math.log2(n))): Forn = 9,int(math.log2(9))is3(levels0, 1, 2, max jump4 + 2 + 1 = 7), which cannot representk = 8(0b1000, needs level3). Using(n - 1).bit_length()gives4levels (0..3), covering everyk <= 8. - Creating
nlists of lengthL(up[v][level]) in Python:100,000separate Python list objects add substantial allocator overhead compared to17lists of length100,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 depthdepth[v], entry timestamptin[v], and per-depth listnodes_at_depth[d](naturally sorted bytin). Ifk > depth[node], return-1; otherwise, binary searchnodes_at_depth[depth[node] - k]for the rightmost node withtin <= tin[node]. UsesO(n)memory instead ofO(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, achievingO(n)preprocessing and memory withO(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 ofnintegers, which takesO(n log n)space (~1.7 million integers forn = 10^5). As quick practical optimizations, you can caplevelsatmax_tree_depth.bit_length()(shrinking the table on shallow, wide trees) and store each row in Python's compactarray('i')(4 bytes per integer instead of 28-byte Pythonintobjects plus 8-byte list pointers). To cut asymptotic memory all the way down toO(n)while preservingO(log n)online queries, replace the jump table with DFS entry timestampstin[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 mostO(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
xundernew_parentalters the ancestors ofxand every vertex insidex's subtree, while leaving vertices outsidex's subtree intact. First verifynew_parentdoes not lie insidex's subtree (which would introduce a cycle), then walkx's subtree top-down in breadth-first order and recomputeup[0..L-1][u]for each subtree vertexuinO(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 supportslink,cut, andk-th ancestor lookups inO(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
aandbis the deepest vertex that is an ancestor of both. Precomputedepth[v]for all vertices during initialization, then lift whichever vertex is deeper byabs(depth[a] - depth[b])viagetKthAncestorso both sit at the exact same depth; ifa == bafterward, returna. Otherwise, scanleveldownward fromself.levels - 1to0and advance bothaandbwheneverup[level][a] != up[level][b], halting one step below the LCA soup[0][a]gives the answer inO(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
- How much memory does the jump table require, and how can you reduce peak space usage to O(n)?
- Suppose edges can be re-assigned at runtime so a node moves under a different parent—how would you adapt your design?
- How can the same power-of-two ancestor table compute the lowest common ancestor of any pair of nodes?
Similar questions
- Upward K-Step Tree Queries with Root Clamping
- 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