DSA interview question
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.
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q); // p and q are in the BST
Input (tree, p, q) | Output | Explanation |
|---|---|---|
([6,2,8,0,4,7,9,null,null,3,5], 2, 8) | 6 | They split at the root |
([6,2,8,0,4,7,9,null,null,3,5], 2, 4) | 2 | A 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.)
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 interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in