KatInterview

Filter Hierarchical Records by Ancestor Validity

Trees & GraphsAuto-graded · 20 test cases
HardAuto-gradedTrees & Graphsgraphsmemoizationcycle-detection

Last 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]): The id of its immediate parent, or None for 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:

  1. Its id appears in allowed_ids.
  2. If its parent_id is not None, then that parent exists in the input and also appears in the output.
  3. 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 id values in the input are unique strings.
  • parent_id is either None or a string.
  • Your solution must run in O(N) average time and use O(N) auxiliary space.
  • allowed_ids may 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.