Problem · Tree
Lowest Common Ancestor with Parent Pointers
Learn this problemProblem statement
You are given a forest of nodes numbered from 0 through n - 1. For each node i, parents[i] is its parent index, or -1 when i is a root.
Return the lowest common ancestor of nodes first and second. A node is considered an ancestor of itself. If the two nodes belong to different trees, return -1.
Use O(1) auxiliary space. The forest is supplied directly through parent links; no root reference is provided.
Function
lowestCommonAncestor(parents: int[], first: int, second: int) → intExamples
Example 1
parents = [-1,0,0,1,1,2,2]first = 3second = 4return = 1Nodes 3 and 4 share node 1 as their nearest ancestor.
Example 2
parents = [-1,0,-1,2,2]first = 1second = 4return = -1Node 1 belongs to the tree rooted at 0, while node 4 belongs to the tree rooted at 2.
Constraints
1 <= parents.length <= 100000.- Every parent is
-1or a valid node index. - The parent links contain no cycle.
firstandsecondare valid node indices.