Filter Hierarchical Records by Ancestor Validity
Trees & GraphsAuto-graded · 20 test casesLast updated
Tests memoized path traversal in a parent-pointer hierarchy with cycle detection and ancestral filtering rules.
You receive a collection of records organized in a hierarchy. Each record is a dictionary containing at least these fields:
"id"(str): A unique string identifying the record."parent_id"(Optional[str]): Theidof its immediate parent, orNonefor root-level records.
You also receive a list allowed_ids containing record IDs that individually meet some criteria.
A record should appear in the output if and only if all of the following hold:
- Its
idappears inallowed_ids. - If its
parent_idis notNone, then that parent exists in the input and also appears in the output. - Following the chain of parent references upward never revisits a previously seen record (no cycles).
In other words, a record is kept when it is allowed, and every ancestor up to a root is also allowed and exists. If any ancestor is disallowed, missing, or part of a cycle, the record and all its descendants are excluded.
Records in the input may appear in any order—children can precede their parents.
Write a function that returns the records to keep, preserving their original order from the input list.
Constraints
0 <= len(tasks) <= 100,000- All
idvalues in the input are unique strings. parent_idis eitherNoneor a string.- Your solution must run in O(N) average time and use O(N) auxiliary space.
allowed_idsmay contain duplicates or IDs not present in the input; these should be ignored.
Examples
Example 1
Input: filter_hierarchy([{'id': 'child', 'parent_id': 'parent', 'name': 'Subtask A'}, {'id': 'unrelated', 'parent_id': None, 'name': 'Standalone Task'}, {'id': 'grandparent', 'parent_id': None, 'name': 'Project Root'}, {'id': 'parent', 'parent_id': 'grandparent', 'name': 'Feature 1'}], ['child', 'unrelated', 'parent'])
Output: [{'id': 'unrelated', 'parent_id': None, 'name': 'Standalone Task'}]
Example 2
Input: filter_hierarchy([{'id': 'A', 'parent_id': 'B'}, {'id': 'B', 'parent_id': 'A'}, {'id': 'C', 'parent_id': None}], ['A', 'B', 'C'])
Output: [{'id': 'C', 'parent_id': None}]
Hints
Hint 1
Walk upward from each record toward the root, but stop early if you reach a record you've already resolved in a previous walk.
Hint 2
Use memoization to mark each record as kept, rejected, or unknown. Once a record's state is determined, reuse it for all descendants.
Hint 3
Detect cycles by tracking which records are on the current upward path. If you encounter a record already on the path, you've found a cycle.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is determining whether each record's entire ancestry chain is valid without repeating work. A naive approach that walks upward from every record independently would take O(N²) time on deep hierarchies.
The solution uses memoization with three states for each record:
0: not yet determined1: keep (record and all ancestors are valid)-1: reject (record, an ancestor, or the chain has a problem)
For each undetermined record, walk upward through parent references and track the path. The walk terminates when one of these conditions occurs:
- Reaching an already-determined record: inherit its state for the entire path below it.
- Encountering a record already on the current path: a cycle exists. Mark all cycle members as rejected and continue with the remaining path prefix.
- Finding a record not in
allowed_ids: the outcome is reject. - Reaching a root (parent_id is None): the outcome is keep.
- Finding a parent_id with no matching record: the outcome is reject.
After the walk completes, propagate the result backward down the path, marking each undetermined record with the outcome. This ensures that when a future walk encounters any of these records, it immediately inherits the correct state without re-traversal.
Finally, scan the original list once and collect records with state 1, preserving input order.
Why It Works
A record is kept only when its upward walk terminates at a valid root, passing through only allowed records. Every record between it and that root was verified or already confirmed valid. If any ancestor is disallowed, missing, or part of a cycle, the walk produces reject and propagates it downward, ensuring descendants are also excluded. Cycles are detected by tracking path membership, preventing infinite loops and correctly rejecting circular dependencies.
Complexity
Time: O(N) average. Building the ID index and allowed set takes O(N). Each record joins at most one path during the entire process. Once marked, it immediately resolves future walks. The final collection scan is O(N).
Space: O(N) for the index map, allowed set, status array, and path tracking structures.
from typing import Dict, List
def filter_hierarchy(tasks: List[Dict], allowed_ids: List[str]) -> List[Dict]:
id_to_index = {task["id"]: i for i, task in enumerate(tasks)}
allowed_set = set(allowed_ids)
status = [0] * len(tasks) # 0: unknown, 1: keep, -1: reject
for start_idx in range(len(tasks)):
if status[start_idx] != 0:
continue
traversal_path = []
path_positions = {}
current_idx = start_idx
result = 0
while True:
if status[current_idx] != 0:
result = status[current_idx]
break
if current_idx in path_positions:
cycle_begin = path_positions[current_idx]
for idx in traversal_path[cycle_begin:]:
status[idx] = -1
traversal_path = traversal_path[:cycle_begin]
result = -1
break
path_positions[current_idx] = len(traversal_path)
traversal_path.append(current_idx)
current_task = tasks[current_idx]
if current_task["id"] not in allowed_set:
result = -1
break
parent_ref = current_task["parent_id"]
if parent_ref is None:
result = 1
break
parent_idx = id_to_index.get(parent_ref)
if parent_idx is None:
result = -1
break
current_idx = parent_idx
for idx in reversed(traversal_path):
if status[idx] == 0:
status[idx] = result
result = status[idx]
return [task for i, task in enumerate(tasks) if status[i] == 1]