FastPrepLowest Common Ancestor in an N-ary Tree

Lowest Common Ancestor in an N-ary Tree

Bloomberg LP logoBloomberg LP● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

A rooted N-ary tree has nodes labeled from 0 through n - 1. It is encoded by parent, where parent[root] = -1 and every other value gives the node's direct parent.

Given two valid node labels p and q, return their lowest common ancestor: the deepest node that is an ancestor of both. 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,3]p = 7q = 4return = 1

Node 1 is the deepest shared ancestor of nodes 7 and 4.

Example 2

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

Both queried nodes are direct children of node 2.

Constraints

  • 1 <= parent.length <= 200000.
  • Exactly one entry is -1; every other entry is a valid node label.
  • The parent relationships form one connected acyclic rooted tree.
  • 0 <= p, q < parent.length.

More Bloomberg LP problems

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