Identify Tree Roots and Trace Ancestor Paths
Trees & GraphsAuto-graded · 18 test casesLast 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
parentIdisNone, or - Its
parentIdreferences an identifier that does not exist among the blocks
Your task is to write a function that computes two things:
- All root identifiers — collect every block that satisfies the root criteria, preserving the order they appear in the input list (without duplicates)
- 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 orNone- 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
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution relies on constructing a hash map that associates each block identifier with its parent reference, enabling constant-time parent lookups.
Finding roots: Iterate through all blocks and check whether each one qualifies as a root. A block meets the root criteria when its parentId field is either None or points to an identifier not present in the collection. We preserve input order and avoid duplicates by collecting qualifying identifiers in sequence.
Tracing the ancestry path: Starting from the target identifier, follow parent pointers upward through the hierarchy. At each step, record the current identifier and move to its parent. Continue until reaching a block whose parent is absent (either None or not in the collection)—this is the root of that branch. Since we collected identifiers from target upward, reverse the sequence to produce the root-to-target ordering.
Why this works: Each non-root block has exactly one parent within the input, creating unambiguous upward chains. Walking upward from any block eventually reaches a root (a block with no valid parent). The path we construct is unique and complete because we follow the single parent chain and stop precisely at the root condition.
Edge cases handled:
- Empty input produces empty roots and empty path
- Missing target returns empty path
- Target that is itself a root produces a path containing only that identifier
- Orphaned blocks (parent not in collection) are correctly identified as roots
Complexity
-
Time: O(n) where n is the number of blocks
- Building the parent map takes O(n)
- Finding roots scans all blocks once: O(n)
- Tracing the path walks at most O(d) steps where d is depth, worst case O(n) for a linear chain
- Overall: O(n)
-
Space: O(n)
- The parent lookup map stores n entries
- The roots list and path list together hold at most n identifiers
- Overall: O(n)
For multiple path queries against the same block collection, build the parent map once and reuse it—each subsequent query then costs O(d) time where d is the depth of that path.
from typing import Dict, List, Optional
def find_root_ids_and_path(blocks: List[Dict[str, Optional[str]]], target_id: str) -> Dict[str, List[str]]:
parent_by_id = {block["id"]: block.get("parentId") for block in blocks}
roots = [
block["id"]
for block in blocks
if block.get("parentId") is None or block.get("parentId") not in parent_by_id
]
if target_id not in parent_by_id:
path = []
else:
path = []
current = target_id
while current in parent_by_id:
path.append(current)
parent = parent_by_id[current]
if parent is None or parent not in parent_by_id:
break
current = parent
path.reverse()
return {"roots": roots, "path": path}