← Questions

Lowest common ancestor with parent pointers

0
MetaCodingLast asked Feb 2026

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's parent is None.

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^5 nodes; the tree can be fully skewed.
  • p and q are in the same tree; they may be the same node.

Clarifying questions

  • Are p and q guaranteed 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 p storing every ancestor in a set, then walk up from q until you hit one. O(h) time and O(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 a from p and b from q upward; when one reaches the top, restart it at the other starting node. They meet at the LCA after at most depth(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

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding