DSA interview question
A company org chart is a binary tree, and HR needs the lowest-ranking manager that both of two employees report up to: their lowest common ancestor (LCA), where a node can be an ancestor of itself. In a plain binary tree there's no ordering to steer the search, so do one post-order DFS. Each call returns p or q if it finds one in its subtree (or the LCA if it finds both). The first node where p and q come back from different sides is the answer.
Example: tree [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4], p = 5, q = 1 → 3; p = 5, q = 4 → 5.
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q); // p and q exist in the tree
Input (tree, p, q) | Output | Explanation |
|---|---|---|
([3,5,1,6,2,0,8,null,null,7,4], 5, 1) | 3 | On opposite sides of the root |
([3,5,1,6,2,0,8,null,null,7,4], 5, 4) | 5 | A node is its own ancestor |
([3,5,1,6,2,0,8,null,null,7,4], 6, 4) | 5 | |
([3,5,1,6,2,0,8,null,null,7,4], 7, 8) | 3 | |
([1, 2], 1, 2) | 1 |
(Confirm: values are unique; both p and q are in the tree; 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