Code Room
CodingMediumcod-g553
Subject Lowest common ancestorLevel Mid–Senior~30 minCommon in Algorithms & data structures interviewsIndustries Software development, Technology

Question

You are given a rooted tree of n nodes labeled 0..n-1 as a parent array (parent[root] = -1). Answer a batch of kth-ancestor queries: for [node, k] return the label of the ancestor reached by going up k edges, or -1 if it does not exist (you walk past the root). Precompute jump pointers (up[j][v] = the 2^j-th ancestor) so each query decomposes k into its binary bits and resolves in O(log n). Return the list of answers in query order.

Implement
kth_ancestor(n: int, parent: list[int], queries: list[list[int]]) → list[int]
Examples
in[7,[-1,0,0,1,1,2,2],[[3,1],[3,2],[5,2],[3,5]]]out[1,0,0,-1]
What a strong answer looks like

State your approach and its time/space complexity out loud before you optimize. Handle the edge cases (empty input, duplicates, overflow), and say why you chose this over the brute force. Green tests are the floor, not the grade.

Vibe coding: describe the solution in plain language (or narrate it) and the coach grades your approach. Generating runnable code from your description is coming next.

Run or narrate your approach, then ask the coach.