Problem · Tree
Lowest Common Ancestor with Parent Pointers
Learn this problemProblem statement
A rooted tree is represented by an integer array parent, where parent[i] is the parent index of node i and the root has parent -1. Given two node indices first and second, return their lowest common ancestor.
The input is a valid rooted tree, and both node indices are valid. Use O(1) auxiliary space: determine both depths by following parent links, lift the deeper node until the depths match, and then move both nodes upward until they meet.
Function
lowestCommonAncestorWithParents(parent: int[], first: int, second: int) → intExamples
Example 1
parent = [-1,0,0,1,1,2,2]first = 3second = 4return = 1Nodes 3 and 4 are both direct children of node 1.
Example 2
parent = [-1,0,0,1,1,2,2]first = 3second = 6return = 0The two nodes lie in different root subtrees, so their lowest common ancestor is node 0.
Constraints
1 <= parent.length <= 100000.parentdescribes one valid rooted tree: exactly one entry is-1, and following parent links from every other node reaches that root.0 <= first, second < parent.length.- The algorithm must use
O(1)auxiliary space.