Answer Many Lowest Common Ancestor Queries Offline in a Folder Tree
Last updated: November 29, 2026
Quick Overview
Given a rooted folder tree as a parent array and a batch of queries (a, b), return the deepest folder that contains both a and b for every query, processing all queries together in near-linear time.
0
0
0 solved
Given a rooted folder tree as a parent array and a batch of queries (a, b), return the deepest folder that contains both a and b for every query, processing all queries together in near-linear time.
Google Drive permission inheritance and shared-folder resolution need common ancestors at scale, and Tarjan's offline LCA is a union-find classic interviewers use to probe depth. The interviewer checks the post-order DFS, the ancestor label kept per set, and answering a query when its second endpoint finishes.
What the Interviewer Expects
- Uses a post-order DFS over the tree
- Merges each finished child into its parent's set
- Keeps an ancestor label at each set root
- Answers a query when the second endpoint finishes, using the other's set label
- Writes the DFS iteratively for deep trees
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Compare with binary lifting for online queries. When would you choose each?
- How would you also return the distance between the two folders?
- What changes if the tree is modified between query batches?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Input:
n,parent_of(with -1 at the root),root, and a list of(a, b)queries. - Output: list of LCA nodes in query order.
- A node is its own ancestor, so
(a, a)returns a....
High-Level Design
Tarjan's algorithm runs a DFS and finishes nodes in post-order. When a node finishes, all of its children's subtrees have been merged into its set, whose label is the node itself. After answering quer...