Lowest Common Ancestor in a Rooted Tree
Problem statement
Each row of pairs is [parent,child]. Return the lowest common ancestor of node IDs a and b.
For this exercise, assume the unique relationships form one rooted tree when nonempty: they are connected, acyclic, and each non-root node has exactly one parent. Repeated copies of an edge have no effect. Only IDs appearing in a pair are represented; empty input represents an empty tree.
For this exercise, assume a node counts as its own ancestor for this LCA query. Return the deepest shared node in the rooted tree. If either query ID is not represented, return -1; this includes empty input.
Function
lowestCommonAncestor(pairs: int[][], a: int, b: int) → intExamples
Example 1
pairs = [[8,2],[8,9],[2,5],[2,6]]a = 5b = 6return = 2This authored tree gives deepest shared node 2 for siblings 5 and 6.
Example 2
pairs = [[1,2],[2,3]]a = 2b = 3return = 2This authored ancestor query returns node 2 itself under the inclusive LCA practice convention.
Constraints
- For this exercise, assume
0 <= pairs.length <= 1000. - Each row contains two positive integer IDs, each at most
10^9. - After duplicate edges are ignored, nonempty input represents one rooted tree.
- For this exercise, assume query IDs are positive integers at most
10^9.