Lowest Common Ancestor in an N-ary Tree
Updated
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) → intExamples
Example 1
parent = [-1,0,0,1,1,2,2,3]p = 7q = 4return = 1Node 1 is the deepest shared ancestor of nodes 7 and 4.
Example 2
parent = [-1,0,0,1,1,2,2]p = 5q = 6return = 2Both 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 Google Phone Screen questions
- Route Pattern MatcherPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Periodic-Color Binary Forest RootsPHONE SCREEN · Seen Nov 2026
- Evaluate a Nested Math ExpressionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Best Stock Trade with Buy and Sell DaysPHONE SCREEN · Seen Nov 2026
- Word Chain Jumps in a GridPHONE SCREEN · Seen Nov 2026
- Dice-Walk Winning ProbabilityPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Apartment Housemate PreferencesPHONE SCREEN · Seen Nov 2026
- Price at Query TimestampsPHONE SCREEN · Seen Nov 2026
- Course Schedule Cycle DetectionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Logger Rate Limiter with Every-Arrival HistoryPHONE SCREEN · Seen Nov 2026
Similar questions at other companies
- File System Shell CommandsHarvey · ONSITE INTERVIEWHarvey interview questions
- In-Memory Filesystem CommandsPerplexity AI · PHONE SCREEN · ONSITE INTERVIEWPerplexity AI interview questions
- Render an Org Chart and Find Skip-Level PairsSnap Inc. · ONSITE INTERVIEWSnap Inc. interview questions
- N-ary Index-Path Encoder and DecoderBloomberg LP · PHONE SCREEN · ONSITE INTERVIEWBloomberg LP interview questions
- Lowest Common Ancestor in an N-ary TreeAmazon · PHONE SCREEN · ONSITE INTERVIEW
- Tree Selection and VisibilityJane Street · PHONE SCREENJane Street interview questions
- Account Roles With Parent-User InheritanceStripe · PHONE SCREENStripe interview questions
- Worst-Performing Ads by CTR in a Campaign TreeUber · PHONE SCREENUber interview questions
- Validate a BST with a Custom ComparisonApple · PHONE SCREENApple interview questions
- JSON Path Lookup with Implicit Array WildcardsMongoDB · ONSITE INTERVIEWMongoDB interview questions