KatInterview

Hierarchical Resource Tree Operations

Data Structure DesignAuto-graded · 13 test cases
MediumAuto-gradedData Structure Designtreeshash-mapsgraphs

Last updated

Tests tree manipulation with parent-child relationships, path reconstruction, and cycle prevention during node relocation.

You will implement a system that manages resources arranged in a tree hierarchy. Each resource has a unique string identifier and may have one parent and multiple children.

Your function receives two parallel lists: operations and arguments. Each operation name corresponds to its arguments at the same index. Process them in order and return a list of results.

Operations

add_resource(resource_id, parent_id)

Insert a new resource as a child of the given parent. If parent_id is None, create a root-level resource. Return None.

  • Raises an error if resource_id already exists
  • Raises an error if parent_id is not None and does not exist

get_path(resource_id)

Return the full path from the root to this resource as a slash-separated string. The path begins with / and includes all ancestors in order.

Example: if C is under B which is under A (a root), return "/A/B/C".

  • Raises an error if resource_id does not exist

move_resource(resource_id, new_parent_id)

Relocate a resource and its entire subtree to a new parent. If new_parent_id is None, the resource becomes a root. Return None on success.

If the move would create a cycle (making a resource its own ancestor), return the string "Cycle detected" and leave the tree unchanged.

  • Raises an error if resource_id does not exist
  • Raises an error if new_parent_id is not None and does not exist
  • Moving a resource to be a child of itself or any of its descendants produces "Cycle detected"

Constraints

  • Resource identifiers are non-empty strings
  • Each resource_id is unique across all add_resource calls
  • Up to 10,000 resources
  • Up to 10,000 operations total
  • The tree may have multiple roots

Examples

Example 1

Input: hierarchical_resource_tree(['add_resource', 'add_resource', 'add_resource', 'get_path', 'move_resource'], [['root', None], ['A', 'root'], ['B', 'A'], ['B'], ['A', 'B']])

Output: [None, None, None, '/root/A/B', 'Cycle detected']

Hints

Hint 1

Store both parent pointers and child sets to enable efficient traversal in both directions.

Hint 2

Build paths by walking upward from a node to its root, then reversing the collected identifiers.

Hint 3

Detect cycles by checking if the resource appears in the ancestor chain of the proposed new parent.