Lowest common ancestor with parent pointers
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Meta's AI-enabled coding round, last asked Feb 2026. It tests trees and pointers.
Each node of a binary tree has value, left, right and parent fields. You are given references to two nodes p and q of the same tree, but not the root. Return their lowest common ancestor: the deepest node that has both as descendants, where a node counts as a descendant of itself. Aim for O(1) extra space.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
lowest_common_ancestor(p: Node, q: Node) -> Node— the root'sparentisNone.
Example
Nodes are numbered 0..6, and parent[i] is the parent of node i:
parent = [-1, 0, 0, 1, 1, 2, 2]
0
/ \
1 2
/ \ / \
3 4 5 6
p = 3, q = 4 -> 1
p = 3, q = 5 -> 0
p = 1, q = 4 -> 1 # p is an ancestor of q
Constraints
- Up to
10^5nodes; the tree can be fully skewed. -
pandqare in the same tree; they may be the same node.
Clarifying questions
- Are
pandqguaranteed to be in the same tree? - Can one be an ancestor of the other, or be the same node?
- Is extra memory allowed, or must it be constant?
What a strong answer covers
- The simple approach: walk up from
pstoring every ancestor in a set, then walk up fromquntil you hit one.O(h)time andO(h)space. - Constant space by depth: compute both depths, lift the deeper node until the depths match, then move both up together until they meet.
- Constant space by two pointers: move
afrompandbfromqupward; when one reaches the top, restart it at the other starting node. They meet at the LCA after at mostdepth(p) + depth(q)steps, like intersecting two linked lists. -
O(h)time,O(1)space. - Tests: siblings, one node an ancestor of the other, the same node twice, nodes in different subtrees of the root, a skewed tree.
Follow-ups
- Without parent pointers, given the root: solve it with one DFS.
- The tree is a binary search tree. How does that make it easier?
- Answer many LCA queries on the same large tree quickly (binary lifting).
Where it's asked
- Meta · AI-enabled coding · Last asked Feb 202660 min · Several progressive tasks on a starter codebase in CoderPad with an AI assistant panel; usually two rounds · The first task usually without AI, later tasks with it
What it tests
trees · pointers
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
