Find root from child adjacency lists
Company: Bloomberg
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of tree data structures, set-based membership reasoning, and algorithmic analysis including time and space complexity and robustness to invalid inputs such as multiple roots or cycles.
Constraints
- All node ids are unique.
- Every non-root node appears exactly once across all children sets.
- A node may appear only as a child (with no record of its own) and is still a valid leaf.
- Return -1 if there is not exactly one root (multiple roots / forest, or a cycle leaving no root).
Examples
Input: [[1, [2, 3]], [2, [4, 5]], [3, []], [4, []], [5, []]]
Expected Output: 1
Explanation: Nodes 2,3,4,5 all appear in some children set; only 1 never does, so 1 is the root.
Input: [[10, [20]], [20, [30]], [30, []]]
Expected Output: 10
Explanation: Linear chain 10 -> 20 -> 30; 10 is never a child, so it is the root.
Hints
- The root is the only node that is never listed as a child of anything. Collect the set of all ids and the set of all child ids — the root is in the first but not the second.
- Build a set of every child id seen across all records, then scan all known ids for the one missing from that child set.
- For invalid-input detection, count how many ids are never anyone's child: exactly one means a valid root; zero (a full cycle) or more than one (a forest) means the input is malformed.