Cheapest Common Ancestor
Updated
Problem statement
A parent array describes a forest of rooted trees. Node i has parent parent[i], or -1 when it is a root. Every node also has a non-negative price prices[i].
A node is considered its own ancestor. Given nodes first and second, return their common ancestor with the smallest price. Break a price tie by the smaller node index. Return -1 when the nodes belong to different trees and have no common ancestor.
Function
cheapestCommonAncestor(parent: int[], prices: int[], first: int, second: int) → intExamples
Example 1
parent = [-1,0,0,1,1,2]prices = [9,5,2,7,4,6]first = 3second = 4return = 1Nodes 1 and 0 are common ancestors; node 1 is cheaper.
Example 2
parent = [-1,0,1,2]prices = [8,3,6,1]first = 1second = 3return = 1Node 1 is its own ancestor and is cheaper than root 0.
Example 3
parent = [-1,-1,0,1]prices = [1,1,2,2]first = 2second = 3return = -1The nodes are in different trees.
Constraints
1 <= parent.length = prices.length <= 200000.parent[i]is-1or a valid node index.- The parent pointers contain no cycle.
0 <= prices[i] <= 1000000000.firstandsecondare valid node indices.
More Google Onsite Interview questions
- Route Pattern MatcherPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Evaluate a Nested Math ExpressionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Distinct Subset SumsONSITE INTERVIEW · Seen Nov 2026
- Playlist With No Same Artist in a RowONSITE INTERVIEW · Seen Nov 2026
- Delete Nodes and Return Forest RootsONSITE INTERVIEW · Seen Nov 2026
- Dice-Walk Winning ProbabilityPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- First and Last Target Position in a Mountain ArrayONSITE INTERVIEW · Seen Nov 2026
- Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- 0/1 Knapsack with Weight and Volume LimitsONSITE INTERVIEW · Seen Nov 2026
- Batched Subsequence Word MatchesONSITE INTERVIEW · Seen Nov 2026
Similar questions at other companies
- File System Shell CommandsHarvey · ONSITE INTERVIEW
- In-Memory Filesystem CommandsPerplexity AI · PHONE SCREEN · ONSITE INTERVIEW
- Render an Org Chart and Find Skip-Level PairsSnap Inc. · ONSITE INTERVIEW
- N-ary Index-Path Encoder and DecoderBloomberg LP · PHONE SCREEN · ONSITE INTERVIEW
- Lowest Common Ancestor in an N-ary TreeAmazon · PHONE SCREEN · ONSITE INTERVIEW
- JSON Path Lookup with Implicit Array WildcardsMongoDB · ONSITE INTERVIEW
- Group Identical Tree LevelsSalesforce · ONSITE INTERVIEW
- Top-Down Employee Reporting ForestOkta · ONSITE INTERVIEW
- Merge N-Ary Trees by KeyLinkedIn · PHONE SCREEN · ONSITE INTERVIEW
- Build a Tree from Preorder and Inorder TraversalsStackAdapt · ONSITE INTERVIEW