Lowest Common Ancestor with Parent Pointers
Updated
Problem 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.
More Salesforce Onsite Interview questions
- Count Increasing TripletsONSITE INTERVIEW · Seen Nov 2026
- Longest Substring Without Repeating CharactersONSITE INTERVIEW · Seen Nov 2026
- Reverse a Sublist of a Linked ListONSITE INTERVIEW · Seen Nov 2026
- Rotting OrangesONSITE INTERVIEW · Seen Nov 2026
- 3Sum SmallerONSITE INTERVIEW · Seen Nov 2026
- Count Zero Request ServersONSITE INTERVIEW · Seen Nov 2026
- Group Identical Tree LevelsONSITE INTERVIEW · Seen Oct 2026
- Meeting Rooms IIONSITE INTERVIEW · Seen Oct 2026
- Construct a Tree from Level-Order and Inorder TraversalsONSITE INTERVIEW · Seen Sep 2026
- Maximize Monsters DefeatedONSITE INTERVIEW · Seen Sep 2026
Similar questions at other companies
- Lowest Common Ancestor with Parent PointersAdobe · ONSITE INTERVIEWAdobe interview questions
- Two Tree Values That Add Up to a TargetExpedia · ONSITE INTERVIEWExpedia interview questions
- First Common Ancestor with Parent PointersMeta · PHONE SCREENMeta interview questions
- Perfect AND Tree Leaf UpdatesPure Storage · ONSITE INTERVIEWPure Storage interview questions
- Swap Adjacent in LR StringGoogle · ONSITE INTERVIEWGoogle interview questions
- Valid Triangle NumberBloomberg LP · PHONE SCREEN · ONSITE INTERVIEWBloomberg LP interview questions
- Path Between Two Nodes of a Fibonacci TreeDatabricks · PHONE SCREEN · ONSITE INTERVIEWDatabricks interview questions
- File System Shell CommandsHarvey · ONSITE INTERVIEWHarvey interview questions
- Merge Sorted Squares of Two ArraysWhatNot · PHONE SCREEN · ONSITE INTERVIEWWhatNot interview questions
- Diagonal Traversal of a Binary TreeAmazon · ONSITE INTERVIEW