← Questions

Lowest common ancestor in an N-ary tree

0
Scale AICodingLast asked Dec 2025

A coding interview question asked in Scale AI's coding round, last asked Dec 2025. It tests trees, dfs and recursion.

Given the root of a rooted N-ary tree (each node has any number of children) and two distinct nodes p and q in it, return their lowest common ancestor: the deepest node that has both p and q in its subtree, where a node counts as being in its own subtree. Do it in one depth-first traversal.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • class Node: val; children: list[Node]
  • lowest_common_ancestor(root: Node, p: Node, q: Node) -> Node.
  • Node values may repeat, so compare nodes by identity, not by value.
  • The DFS helper returns a pair of booleans: whether p and whether q is in the current subtree. The first node, in post-order, whose pair is (True, True) is the answer.

Example

            1
       /    |    \
      2     3     4
     / \         / \
    5   6       7   8

lowest_common_ancestor(root, node5, node8)  ->  node1
lowest_common_ancestor(root, node5, node6)  ->  node2
lowest_common_ancestor(root, node4, node7)  ->  node4    # a node is its own descendant

Constraints

  • Up to 10^5 nodes; the tree may be very unbalanced (a chain).
  • p and q are distinct and both in the tree.

Clarifying questions

  • Are p and q guaranteed to be in the tree?
  • Can one be an ancestor of the other?
  • Are values unique, or must we compare node references?
  • Do nodes have parent pointers?

What a strong answer covers

  • Post-order DFS returning (found_p, found_q): combine the children's pairs with the current node, and record the first node where both are true. Stop early once found.
  • O(n) time and O(h) stack space; why recursion can overflow on a 10^5-node chain, and an iterative version with an explicit stack.
  • The case where one node is the ancestor of the other.
  • Comparing by identity.
  • Tests with the examples, a chain, and the root as one of the nodes.

Follow-ups

  • Nodes have parent pointers. Find the LCA without the root, in O(depth) time and O(1) space.
  • Answer many LCA queries on the same tree quickly (binary lifting, or an Euler tour with a range-minimum structure).
  • Find the LCA of a set of k nodes.

Where it's asked

  • Scale AI · Coding · Last asked Dec 2025Live coding, one or two rounds, Python

What it tests

trees · dfs · recursion

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