FastPrepLowest Common Ancestor in a Parent Tree

Lowest Common Ancestor in a Parent Tree

BlackRock logoBlackRock● EasyNEW GRADOA
Learn

Problem statement

A rooted tree with nodes 0 through n - 1 is represented by parent. The root is node 0, parent[0] = -1, and for every other node i, parent[i] is its direct parent.

Given nodes p and q, return their lowest common ancestor: the common ancestor farthest from the root. A node is an ancestor of itself.

Function

lowestCommonAncestor(parent: int[], p: int, q: int) → int

Examples

Example 1

parent = [-1,0,0,1,1,2,2]p = 3q = 4return = 1

Nodes 3 and 4 are both direct children of node 1.

Example 2

parent = [-1,0,0,1,1,2,2]p = 3q = 6return = 0

The two nodes lie in different root subtrees.

Constraints

  • 1 <= parent.length <= 100000.
  • parent[0] = -1.
  • For i > 0, 0 <= parent[i] < i.
  • 0 <= p, q < parent.length.

More BlackRock problems

See BlackRock hiring insights
public int lowestCommonAncestor(int[] parent, int p, int q) {
    // Write your code here.
}
parent[-1,0,0,1,1,2,2]
p3
q4
expected1
Checking account…