Code Room
CodingHardcod-g300
Subject Lowest common ancestorLevel Senior–Staff~40 minCommon in Algorithms & data structures interviewsIndustries Software development, Technology

Question

You are given a rooted tree with n nodes labeled 0..n-1 as a parent array, where parent[i] is the parent of node i and parent[r] == -1 for the unique root r. Answer a batch of LCA queries: for each [u, v] return the label of their lowest common ancestor. Preprocess so each query is answered in O(log n). Return the list of answers in query order.

Implement
lca_binary_lifting(n: int, parent: list[int], queries: list[list[int]]) → list[int]
Examples
in[7,[-1,0,0,0,1,1,3],[[4,5],[4,2],[6,4],[6,3],[0,6],[5,5]]]out[1,0,0,3,0,5]
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.