← Questions

Validate a parent-child forest

0
WaymoCodingLast asked May 2026

A coding interview question asked in Waymo's technical phone screen, last asked May 2026. It tests graphs, trees and union-find.

Given a list of parent-child pairs, decide whether they describe a valid forest: a set of rooted trees where every node has at most one parent, there are no cycles, and each tree has exactly one root. When the input is not valid, say why.

Interface

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

  • validate_forest(pairs: list[tuple[str, str]]) -> tuple[bool, str | None] — each pair is (parent, child); returns (True, None) or (False, reason) with a reason such as "two parents: c", "cycle: a" or "self loop: a". Nodes are every name that appears in a pair.

Example

validate_forest([("a","b"), ("a","c"), ("d","e")])   ->  (True, None)          # two trees, roots a and d
validate_forest([("a","c"), ("b","c")])              ->  (False, "two parents: c")
validate_forest([("a","b"), ("b","c"), ("c","a")])   ->  (False, "cycle: a")   # no root at all
validate_forest([("a","a")])                         ->  (False, "self loop: a")
validate_forest([])                                  ->  (True, None)          # the empty forest

Constraints

  • Up to 10^5 pairs. A duplicate pair should be treated as an error or ignored; agree which.

Clarifying questions

  • Are duplicate pairs allowed?
  • Can a node exist with no pairs (an isolated root)?
  • Is an empty input valid?
  • Which reason should be reported when several problems exist?
  • Is a cycle detached from every root possible, and how should it be named?

What a strong answer covers

  • Pass one: count parents per child; any child with two parents fails at once (and a self pair is its own case).
  • With at most one parent each, the structure is a set of paths upward; a cycle is the only remaining failure. Find it with a DFS from each root (every node must be reached from some root) or by following parent pointers with a visited state.
  • Union-find as an alternative: an edge joining two nodes already in the same set means a cycle.
  • O(nodes + pairs) time and memory; a deterministic choice of which reason to report.
  • Tests for each failure, the empty input, and many disjoint trees.

Follow-ups

  • Report every problem, not just the first.
  • The pairs arrive one at a time; reject the first pair that breaks the forest.
  • Return the trees, each as a nested structure from its root.

Where it's asked

  • Waymo · Technical phone screen · Last asked May 202645 min · Coding: a classic algorithm problem or an original, under-specified problem framed around self-driving

What it tests

graphs · trees · union-find

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