Find LCA in a BST
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: This interview question evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer for Find LCA in a BST states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Read the full Amazon Software Engineer interview experience this question came from
Constraints
- 0 <= len(insert_order) <= 10^4
- 0 <= node values <= 10^9 (all non-negative so -1 is an unambiguous 'not found' sentinel)
- All values in insert_order are distinct (duplicates are ignored on insertion)
- p and q are integers; they may or may not be present in the BST
Examples
Input: ([6, 2, 8, 0, 4, 7, 9, 3, 5], 2, 8)
Expected Output: 6
Explanation: 2 lives in the left subtree and 8 in the right subtree of the root, so the root 6 is the split point and the LCA.
Input: ([6, 2, 8, 0, 4, 7, 9, 3, 5], 2, 4)
Expected Output: 2
Explanation: 4 is a descendant of 2, so the deeper ancestor common to both is 2 itself.
Hints
- Reconstruct the BST first: walk down from the root for each value, going left when smaller and right when larger, attaching a new node where you fall off the tree.
- Use the BST property for the LCA: the lowest common ancestor is the first node (from the root) whose value lies between p and q inclusive. If the node is greater than both keys go left; if less than both go right; otherwise it is the answer.
- Before searching, verify both p and q actually exist in the tree with two ordinary BST lookups — return -1 if either lookup fails or the tree is empty.