Find cheapest common ancestor in a tree
Company: Google
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates understanding of tree data structures and ancestor concepts (such as lowest common ancestor) along with algorithmic skills for aggregating node attributes like minimum values, situating it in the Coding & Algorithms domain and testing practical application backed by conceptual understanding of ancestor relationships.
Constraints
- 1 <= n == len(parent) == len(prices) <= 10^5
- The input forms a valid rooted tree with exactly one root
- -10^9 <= prices[i] <= 10^9
- 0 <= a, b < n
- a and b belong to the same tree and may be equal
Examples
Input: ([-1, 0, 0, 1, 1, 2, 2], [10, 5, 8, 7, 2, 6, 1], 3, 4)
Expected Output: 1
Explanation: The common ancestors of nodes 3 and 4 are 1 and 0. Their prices are 5 and 10, so node 1 is the cheapest.
Input: ([-1, 0, 0, 1, 1, 2, 2], [10, 5, 8, 7, 2, 6, 1], 5, 6)
Expected Output: 2
Explanation: The common ancestors of nodes 5 and 6 are 2 and 0. Their prices are 8 and 10, so node 2 is the cheapest.
Input: ([-1, 0, 1, 1], [4, -3, 10, -3], 2, 2)
Expected Output: 1
Explanation: Since a and b are the same node, the common ancestors are 2, 1, and 0. Their prices are 10, -3, and 4, so node 1 is the cheapest.
Input: ([-1, 0, 1, 2], [5, 1, 1, 7], 3, 2)
Expected Output: 2
Explanation: The common ancestors are 2, 1, and 0. Nodes 2 and 1 both have price 1, so the tie is broken by choosing the deeper node, which is 2.
Input: ([-1, 0, 1, 2, 3], [0, 9, -5, 4, -5], 4, 1)
Expected Output: 0
Explanation: The common ancestors of 4 and 1 are 1 and 0. Their prices are 9 and 0, so node 0 is the cheapest.
Hints
- A node can only be a common ancestor if it lies on both paths from a and b up to the root.
- First find the lowest common ancestor by equalizing depths using parent pointers. Then only the ancestors of that node need to be checked for the minimum price.