FastPrepLowest Common Ancestor in an N-ary Tree
Problems/Lowest Common Ancestor in an N-ary Tree

Lowest Common Ancestor in an N-ary Tree

Bloomberg LP logoBloomberg LP● MediumFULLTIMEPHONE SCREEN
QuestionFunctionExamplesConstraints

Problem statement

Source note: The report names the N-ary-tree lowest-common-ancestor task but omits a portable tree representation and bounds. A parent-array adapter is defined for practice; the judged task matches at about 96%.

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

  • Mutable Stock Price Top KPHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2026
  • Sparse Vector and Matrix OperationsPHONE SCREEN · Seen Oct 2026
  • Add Two Numbers IIPHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2026
All Bloomberg LP interview questionsSee Bloomberg LP hiring insights
Saved
class Solution {
    public int lowestCommonAncestor(int[] parent, int p, int q) {
        // Write your code here.
    }
}
Checking account…