Hierarchical Resource Tree Operations
Data Structure DesignAuto-graded · 13 test casesLast 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_idalready exists - Raises an error if
parent_idis notNoneand 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_iddoes 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_iddoes not exist - Raises an error if
new_parent_idis notNoneand 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_idis unique across alladd_resourcecalls - 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
We maintain two hash maps to represent the tree structure:
- Parent map: maps each resource identifier to its parent (or
Nonefor roots) - Child sets: maps each resource identifier to a set of its direct children
These dual structures enable efficient upward and downward traversal.
Adding a resource inserts entries into both maps and links the child to its parent's set in constant time.
Getting a path walks upward from the resource to a root by following parent pointers, collecting identifiers along the way. We then reverse this list and join with slashes to produce the root-to-node path.
Moving a resource requires cycle detection. A cycle occurs if and only if the resource being moved appears in the ancestor chain of the proposed new parent. We walk upward from the new parent; if we encounter the resource, we reject the move and return "Cycle detected". Otherwise, we detach the resource from its old parent's child set, update its parent pointer, and add it to the new parent's child set. The entire subtree moves automatically since descendants still point to the resource through their parent chains.
Why It Works
The tree remains acyclic as long as we reject moves that would create cycles. By checking whether the resource lies on the new parent's path to a root, we ensure that updating the parent pointer cannot introduce a loop. All other tree properties (unique parents, consistent child sets) are maintained by the bookkeeping in each operation.
Complexity
Let n be the number of resources and d be the depth of the relevant node.
- add_resource: O(1) average – dictionary inserts and set additions
- get_path: O(d) – one walk to the root plus string joining
- move_resource: O(d) – ancestor walk from the new parent; detach and attach are O(1)
Space complexity is O(n) for the two maps. In the worst case (a linear chain), d can equal n, but operations remain efficient for the given constraints.
from typing import List, Optional
def hierarchical_resource_tree(operations, arguments):
parent_map = {}
child_sets = {}
output = []
for op, args in zip(operations, arguments):
if op == "add_resource":
res_id, par_id = args
if res_id in parent_map:
raise ValueError("resource already exists")
if par_id is not None and par_id not in parent_map:
raise ValueError("parent does not exist")
parent_map[res_id] = par_id
child_sets[res_id] = set()
if par_id is not None:
child_sets[par_id].add(res_id)
output.append(None)
elif op == "get_path":
res_id = args[0]
if res_id not in parent_map:
raise KeyError(res_id)
path_parts = []
node = res_id
while node is not None:
path_parts.append(node)
node = parent_map[node]
output.append("/" + "/".join(reversed(path_parts)))
elif op == "move_resource":
res_id, new_par_id = args
if res_id not in parent_map:
raise KeyError(res_id)
if new_par_id is not None and new_par_id not in parent_map:
raise ValueError("new parent does not exist")
# Check for cycle by walking up from new parent
node = new_par_id
creates_cycle = False
while node is not None:
if node == res_id:
creates_cycle = True
break
node = parent_map[node]
if creates_cycle:
output.append("Cycle detected")
continue
old_par_id = parent_map[res_id]
if old_par_id is not None:
child_sets[old_par_id].remove(res_id)
parent_map[res_id] = new_par_id
if new_par_id is not None:
child_sets[new_par_id].add(res_id)
output.append(None)
else:
raise ValueError("unknown operation")
return output