KatInterview

Identify Tree Roots and Trace Ancestor Paths

Trees & GraphsAuto-graded · 18 test cases
MediumAuto-gradedTrees & Graphsgraphstreeshash-maps

Last updated

Tests graph traversal, parent-pointer navigation, and root identification in tree-like structures represented as parent references.

You receive a list of blocks, where each block is a dictionary containing an "id" (string) and a "parentId" (string or None).

A block qualifies as a root when either:

  • Its parentId is None, or
  • Its parentId references an identifier that does not exist among the blocks

Your task is to write a function that computes two things:

  1. All root identifiers — collect every block that satisfies the root criteria, preserving the order they appear in the input list (without duplicates)
  2. Ancestry path for a target — given a target_id, trace the chain of parent references from the topmost ancestor (root) down to the target itself

Return a dictionary with two keys:

  • "roots": a list of strings containing all root identifiers
  • "path": a list of strings forming the path from root to target (empty list if the target doesn't exist)

If the target identifier is not present in the input blocks, the path should be an empty list.

Constraints

  • 0 ≤ number of blocks ≤ 10⁵
  • All "id" values are unique strings
  • "parentId" is either a string or None
  • The target identifier is a string
  • No cycles exist in the parent references (you may assume valid tree structure)
  • Path should be ordered from root to target (ancestor to descendant)

Examples

Example 1

Input: find_root_ids_and_path([{'id': 'a', 'parentId': None}, {'id': 'b', 'parentId': 'a'}, {'id': 'c', 'parentId': 'missing'}, {'id': 'd', 'parentId': 'b'}], 'd')

Output: {'roots': ['a', 'c'], 'path': ['a', 'b', 'd']}

Example 2

Input: find_root_ids_and_path([{'id': 'root', 'parentId': None}, {'id': 'child', 'parentId': 'root'}], 'root')

Output: {'roots': ['root'], 'path': ['root']}

Example 3

Input: find_root_ids_and_path([{'id': 'a', 'parentId': None}, {'id': 'b', 'parentId': 'a'}], 'missing')

Output: {'roots': ['a'], 'path': []}

Hints

Hint 1

Build a lookup table mapping each identifier to its parent for constant-time access

Hint 2

A block is a root when its parent is absent or points to a non-existent identifier—check both conditions

Hint 3

To build the path, start at the target and walk upward through parents, then reverse the collected sequence