PPractick

DSA interview question

Lowest Common Ancestor in a BST

Medium · Algorithms · Topics: bst, recursion

The problem

A file index is stored as a BST keyed by ID, and a sync tool often needs the lowest common ancestor of two entries. In a plain binary tree that takes a full DFS, but a BST's ordering pinpoints it with a single walk from the root. If both keys are smaller than the current node, the LCA is in the left subtree; if both are larger, it's on the right. The first node where they split (one on each side, or one of them equal to the node) is the LCA.

Example: BST [6, 2, 8, 0, 4, 7, 9, null, null, 3, 5], p = 2, q = 8 → 6; p = 2, q = 4 → 2.

Function signature

TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q);  // p and q are in the BST

Test cases

Input (tree, p, q)OutputExplanation
([6,2,8,0,4,7,9,null,null,3,5], 2, 8)6They split at the root
([6,2,8,0,4,7,9,null,null,3,5], 2, 4)2A node is its own ancestor
([6,2,8,0,4,7,9,null,null,3,5], 3, 5)4
([6,2,8,0,4,7,9,null,null,3,5], 7, 9)8
([2, 1], 2, 1)2

(Confirm: keys are distinct; both nodes exist; a node may be its own ancestor.)

How interviewers phrase it

Clarifying questions to ask

  1. Is it a BST? (Yes, which enables the O(h) walk.)
  2. Are both nodes guaranteed to be in the tree? (Yes.)
  3. Can p be an ancestor of q? (Yes: then p is the answer.)

Follow-ups to expect

  1. "Why is the split point the LCA?"
  2. "Iterative or recursive?"
  3. "What if p or q might be missing?"
  4. "How does it compare with the binary-tree LCA?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in