Find LCA in a N-ary tree via DFS
Company: Scale AI
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of tree algorithms and recursive DFS traversal for computing the lowest common ancestor in an N-ary tree, including handling node references, subtree detection, and correctness in a single traversal.
Constraints
- 1 <= number of nodes <= 10^5
- The tree may be highly unbalanced
- Node ids are unique, but node values may repeat
- p_id and q_id are distinct and both exist in the tree
Examples
Input: ((1, 100, [(2, 200, [(5, 500, []), (6, 600, [])]), (3, 300, []), (4, 400, [(7, 700, []), (8, 800, [])])]), 5, 8)
Expected Output: 1
Explanation: Node 5 is in the subtree of 2 and node 8 is in the subtree of 4, so their lowest common ancestor is the root node 1.
Input: ((1, 100, [(2, 200, [(5, 500, []), (6, 600, [])]), (3, 300, []), (4, 400, [(7, 700, []), (8, 800, [])])]), 5, 6)
Expected Output: 2
Explanation: Nodes 5 and 6 are both direct children of node 2, so node 2 is their LCA.
Hints
- Let each DFS call return two booleans: whether p was found in the current subtree and whether q was found in the current subtree.
- Use postorder traversal. If children are processed before the current node, the first node whose returned pair becomes (True, True) is the deepest common ancestor.