Answer Many Kth Ancestor Queries on a Large Binary Tree

Last updated: November 29, 2026

Quick Overview

Given a binary tree with n nodes labeled 0 to n-1 via a parent array, answer many queries of the form: return the kth ancestor of node v, or -1 if it does not exist.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

0

0 solved


Given a binary tree with n nodes labeled 0 to n-1 via a parent array, answer many queries of the form: return the kth ancestor of node v, or -1 if it does not exist.

A Google onsite hard question that tests preprocessing for repeated queries, in the style of walking up a large build dependency hierarchy. The interviewer looks for binary lifting and a clear statement of the time and memory trade-off.

What the Interviewer Expects
  • Note that walking up k steps per query is O(k)
  • Build jump tables up[j][v] for 2^j ancestors
  • Decompose k into powers of two to answer queries
  • State O(n log n) preprocessing and O(log k) per query
  • Discuss an offline alternative using DFS and a path stack
Key Topics to Cover
binary trees
binary lifting
sparse tables
preprocessing
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • Answer the queries offline in O(n + q) total.
  • Use the same table to compute lowest common ancestors.
  • What if nodes are added as leaves over time?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

Input: parent list of length n where parent[0] = -1 is the root, plus queries (v, k). Output: kth ancestor for each query, -1 if k exceeds the depth of v. The tree is binary but the technique do...

High-Level Design

Precompute up[j][v], the 2^j-th ancestor of v. up[0] is the parent array. Then up[j][v] = up[j-1][ up[j-1][v] ], with -1 propagating. LOG is the number of bits of n, because no ancestor is more ...


Submit Your Answer
Markdown supported