FastPrepLowest Common Ancestor in a Rooted Tree

Lowest Common Ancestor in a Rooted Tree

Intuit logoIntuit● MediumNEW GRADPHONE SCREEN
Learn

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) → int

Examples

Example 1

pairs = [[8,2],[8,9],[2,5],[2,6]]a = 5b = 6return = 2

This authored tree gives deepest shared node 2 for siblings 5 and 6.

Example 2

pairs = [[1,2],[2,3]]a = 2b = 3return = 2

This 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.

More Intuit problems

See Intuit hiring insights
public int lowestCommonAncestor(int[][] pairs,int a,int b) {
    // Write your code here.
    return -1;
}
pairs[[8,2],[8,9],[2,5],[2,6]]
a5
b6
expected2
Checking account…