← Questions

Cheapest common ancestor in a tree

0
GoogleCodingLast asked Feb 2026

A coding interview question asked in Google's onsite coding round, last asked Feb 2026. It tests trees and dfs.

Every node of a rooted tree has a cost. Given a set of nodes, return the common ancestor of all of them with the lowest cost. A node counts as an ancestor of itself.

Interface

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

  • cheapest_common_ancestor(parent: list[int], cost: list[int], nodes: list[int]) -> int — parent[i] is the parent of node i, or -1 for the root; returns the node id.
  • On equal costs, return the deeper node.

Example

        0 (5)
       /     \
    1 (8)    2 (1)
    /   \       \
  3 (2)  4 (9)  5 (4)
  /
6 (7)

parent = [-1, 0, 0, 1, 1, 2, 3],  cost = [5, 8, 1, 2, 9, 4, 7]

nodes = [6, 4]  ->  0     # common ancestors 1 and 0; 0 is cheaper
nodes = [3, 6]  ->  3     # 3 is an ancestor of 6 and of itself
nodes = [6, 5]  ->  0     # only the root is common
nodes = [5]     ->  2     # 5, 2 and 0 are candidates

Constraints

  • nodes is non-empty and every id is a node of the tree.
  • Costs are integers.

Clarifying questions

  • Is the tree given as parent pointers, child lists or node objects?
  • Does a node count as its own ancestor?
  • How are ties in cost broken?
  • Is this one query, or many queries on the same tree?

What a strong answer covers

  • The common ancestors of a set are exactly the path from their lowest common ancestor up to the root, so the answer is the cheapest node on that path.
  • Finding the LCA of many nodes by folding pairwise LCA, or in one DFS that counts how many query nodes each subtree holds.
  • O(n) for one query; with many queries, binary lifting that stores the minimum cost along each jump, for O(log n) per pair.
  • Edge cases: one node, a node that is an ancestor of the others, the root.

Follow-ups

  • Answer many queries fast on a fixed tree.
  • Costs change between queries.
  • The input is a DAG where a node can have several parents.

Where it's asked

  • Google · Onsite coding · Last asked Feb 202645 min · Usually two rounds, mostly in person: whiteboard plus a Chromebook with Google Docs · No AI (a pilot code-comprehension round lets candidates use Gemini)

What it tests

trees · dfs

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