DSA

Lowest Common Ancestor Interview Questions

How would you find the lowest common ancestor (LCA) in a binary tree? — spoken sample answer for Indian interviews.

  • 5Questions with answers
  • 3Difficulty levels

Questions (5)

Browse beginner, intermediate, and advanced questions with answers — hide them when you want to self-test.

Question 1
Interview Intermediate
Question

How would you find the lowest common ancestor (LCA) in a binary tree?

Answer:

Find the deepest node that is an ancestor of both nodes p and q.

Optimal (general tree): If current node is p or q, return it. Recurse left and right. If both sides return non-null, current is LCA; else return the non-null side. Complexity: Time O(n) , Space O(height)

Optimal (BST): Walk from root — both smaller go left, both larger go right, otherwise current node is the split point. Complexity: Time O(height)

With parent pointers, store ancestors of one node in a set and climb the other.

Question 2
Interview Intermediate
Question

How do you find LCA in a BST versus in a binary tree?

Answer:

In a BST I can walk from the root: if both nodes are less, go left; both greater, go right; otherwise this node is the split and the LCA. That is O(h) and I do not need parent pointers. In a general binary tree I DFS and return a node if I found p or q in that subtree. If both sides return non-null, I am the LCA. I would not search BST with the general method first — they want the property.

Question 3
Interview Intermediate
Question

What if a node is not in the tree?

Answer:

I would not assume both p and q exist. I search, and if one is missing I must not return the other as LCA unless the problem says a node can be an ancestor of itself and both exist. LeetCode 236 assumes both exist. In a real interview I ask. Implementation: count found nodes or do an extra exists check. Silent wrong LCA is worse than a clarifying question.

Question 4
Interview Beginner
Question

How do you find LCA if nodes have parent pointers?

Answer:

I walk from p to root and store the path in a set, then walk from q until I hit the set. Or I compute depths and climb the deeper one, then climb together. Both are O(h) . Parent pointers make it like linked-list intersection. I would mention that analogy. If parents are missing I fall back to the DFS method.

Question 5
Interview Advanced
Question

Can you find LCA of more than two nodes?

Answer:

Yes. I can reduce: LCA of a set is LCA(x, LCA of the rest). On a BST I still walk until the nodes are not all on one side. On a general tree I DFS and return when I have collected all targets in a subtree. I would ask whether the nodes are guaranteed to exist. This is a natural extension if I finished two-node LCA early.

Practice with AI mock interviews

Run DSA mock interviews with AI follow-ups, instant feedback, and analytics on AiLx.

Free to start · No credit card required