← Questions

Root of the largest tree in a forest

0

A coding interview question asked at Google and Microsoft. It tests trees, graphs and dfs.

You are given a list relations. Each entry [child, parent] says that parent is the direct parent of child. Together the relations form a forest: there are no cycles, and every node has at most one parent. Node IDs are integers, and the forest contains only the nodes that appear in relations.

A root is a node that appears in relations but never as a child. The size of a tree is the number of distinct nodes in it, root included.

Implement:

def largest_tree_root(relations: list[list[int]]) -> int | None

The function returns the root of the tree with the largest size. If two or more trees have the same size, return the smallest root ID. If relations is empty, return None.

Constraints

  • 0 <= len(relations) <= 10^5
  • Node IDs are non-negative integers up to 10^9.
  • A tree can be a single chain up to 10^5 nodes deep.

Example 1

relations = [[4, 9], [7, 9], [1, 7], [3, 2]]

The tree rooted at 9 holds {9, 4, 7, 1}, so its size is 4. The tree rooted at 2 holds {2, 3}, so its size is 2. Answer: 9.

Example 2

relations = [[15, 20], [16, 20], [31, 30], [32, 30]]

Both trees have 3 nodes, so the smaller root wins. Answer: 20.

Clarifying questions

  • Can the same [child, parent] pair appear twice, and is it still one edge?
  • Should the function check the input for cycles or for a node with two parents, or can we trust it?
  • Do we need only the root, or also the size?
  • Can relations arrive one by one, with the answer asked after each?

What a strong answer covers

  • Builds a parent map and a children map. The roots are the parents that never appear as a child.
  • Counts each tree's size with an iterative BFS or DFS from its root. Or uses union-find with sizes, or memoizes each node's root while walking up. All of these are O(n).
  • Uses dicts, not arrays, because ids go up to 10^9.
  • Avoids recursion, since a chain can be 10^5 deep.
  • Applies the tie rule (smallest root id) and returns None for empty input.
  • Tests the two examples, a single deep chain, duplicate pairs, and one node with many children.

Follow-ups

  • Return the depth of the deepest tree as well.
  • Relations stream in: keep the answer current with union-find by size.
  • The input may be invalid (cycles or two parents): detect it and report where.
  • Return the sizes of all trees, sorted.

Where it's asked

What it tests

trees · graphs · dfs · hash map

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