Lowest Common Ancestor in a Rooted Tree
Updated
Problem statement
Given a rooted tree, return the lowest common ancestor of node IDs a and b: the deepest node that is an ancestor of both requested nodes.
For this exercise, assume root is the root ID and each row of pairs is a distinct relationship [parent,child]. The pairs form one valid general tree rooted at root, with any number of children per node. Pair order does not matter. The represented nodes are the root and every pair endpoint; an empty pair list represents the one-node tree containing only the root.
For this exercise, assume both query IDs are represented, a node is its own ancestor, and equal query IDs are allowed. Return the unique lowest common ancestor as one integer ID. Do not modify the input.
Function
lowestCommonAncestor(root: int, pairs: int[][], a: int, b: int) → intExamples
Example 1
root = 8pairs = [[8,2],[8,9],[2,5],[2,6]]a = 5b = 6return = 2This general tree gives siblings 5 and 6 the deepest shared ancestor 2.
Example 2
root = 1pairs = [[1,2],[1,3],[1,4],[3,5]]a = 2b = 5return = 1The queries lie in different root branches, so their lowest common ancestor is 1.
Example 3
root = 7pairs = []a = 7b = 7return = 7The explicit root represents a one-node tree. Under inclusive ancestry, its LCA with itself is 7.
Constraints
- For this exercise, assume
1 <= N <= 200represented nodes andpairs.length = N - 1. - Every pair contains two integer IDs from
0through10^6; the root and both queries use that domain. - For this exercise, assume no duplicate edges or cycles, every non-root node has exactly one parent, and every represented node is reachable from the root.
More Karat interview questions
Similar questions at other companies
- Diagonal Traversal of a Binary TreeAmazon · ONSITE INTERVIEW
- Render an Org Chart and Find Skip-Level PairsSnap Inc. · ONSITE INTERVIEWSnap Inc. interview questions
- Find Leaves of a Binary TreeLinkedIn · ONSITE INTERVIEWLinkedIn interview questions
- N-ary Index-Path Encoder and DecoderBloomberg LP · PHONE SCREEN · ONSITE INTERVIEWBloomberg LP interview questions
- Delete Nodes and Return Forest RootsGoogle · ONSITE INTERVIEWGoogle interview questions
- Render a Task Tree from CSV RowsStripe · PHONE SCREEN · ONSITE INTERVIEWStripe interview questions
- Filter Undesired Comments and Their DescendantsReddit · PHONE SCREEN · ONSITE INTERVIEWReddit interview questions
- JSON Path Lookup with Implicit Array WildcardsMongoDB · ONSITE INTERVIEWMongoDB interview questions
- Delete and Compact a Forest SubtreePinterest · PHONE SCREEN · ONSITE INTERVIEWPinterest interview questions
- Onion-Peel Layers of a Binary TreeeBay · ONSITE INTERVIEWeBay interview questions