Find LCA With Parent Pointers
Company: Bytedance
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of tree data structures and ancestor relationships, focusing on lowest common ancestor reasoning with parent pointers and attention to time and space complexity constraints.
Constraints
- 1 <= len(parents) <= 200000
- parents[i] is either -1 or an integer in the range [0, len(parents) - 1]
- There is exactly one root, and its parent is -1
- 0 <= a, b < len(parents)
- Both nodes belong to the same tree
Examples
Input: ([-1,0,0,1,1,2,2], 3, 4)
Expected Output: 1
Explanation: Node 3 goes 3 -> 1 -> 0 and node 4 goes 4 -> 1 -> 0, so their lowest common ancestor is 1.
Input: ([-1,0,0,1,1,3], 1, 5)
Expected Output: 1
Explanation: Node 1 is an ancestor of node 5, and a node is considered an ancestor of itself.
Input: ([-1,0,0,1,1,3,5], 6, 4)
Expected Output: 1
Explanation: Node 6 goes 6 -> 5 -> 3 -> 1 -> 0 and node 4 goes 4 -> 1 -> 0, so the deepest shared ancestor is 1.
Input: ([-1,0,0,1,1,2,2], 5, 4)
Expected Output: 0
Explanation: Node 5 is in the subtree of 2 and node 4 is in the subtree of 1, so they first meet at the root 0.
Input: ([-1,0,0,1], 3, 3)
Expected Output: 3
Explanation: Both inputs are the same node, so that node is its own lowest common ancestor.
Input: ([-1], 0, 0)
Expected Output: 0
Explanation: In a single-node tree, the only node is the LCA of itself.
Hints
- Think of the path from each node up to the root as a singly linked list. The LCA is where those two lists first intersect.
- There is an O(1) space linked-list intersection trick: when one pointer reaches the end, restart it from the other node.