Path-Addressed Tree Store: Replay a Command Log
Data Structure DesignAuto-graded · 15 test casesLast updated
Simulate a path-keyed tree store by replaying a list of commands, testing trie or hash-map design, path validation, and exact failure semantics.
You are building a small in-memory store whose entries are arranged as a tree and addressed by slash-separated absolute paths. Instead of a class, you implement one function that replays a log of commands against a fresh, empty store and returns one result per command.
The store
- The tree always contains a root node at path
/, whose initial value is the string"#". - Every node holds a string value. The empty string is a legitimate value.
- A node is identified by its absolute path, for example
/a/b/c.
Valid paths
A path is valid if all of the following hold:
- It is a string that starts with
/. - It is exactly
/(the root), or it is/followed by one or more segments separated by single/characters. - No segment is empty,
., or... This rules out//, trailing slashes such as/a/, and relative-style segments.
Anything else (for example "", a/b, /a/, /a//b, /a/./b, /a/../b) is invalid.
Commands
Each command is a name plus an argument list. Commands are applied in order, and each produces one result.
| Command | Arguments | Behavior | Result |
|---|---|---|---|
create | [path, value] | Add a new node with the given value. The path must be valid and not the root, the parent node must exist, and the node itself must not already exist. | true on success, otherwise false |
set_value | [path, value] | Overwrite the value of an existing node (the root is allowed). | true on success, otherwise false |
get_value | [path] | Read the value of an existing node (the root is allowed). | the value string, or null if the path is invalid or the node does not exist |
delete | [path] | Remove an existing node that has no children. The root can never be deleted. | true on success, otherwise false |
Additional rules:
- A failed command must leave the store unchanged.
- If a command has the wrong number of arguments,
create,set_valueanddeletereturnfalse, andget_valuereturnsnull. - If the command name is not one of the four above, the result is
null. - After a node is deleted, the same path may be created again, and the new node starts with no children.
Task
Implement replay_tree_store(commands, command_args), where commands[i] is the name of the i-th command and command_args[i] is its list of string arguments. Return a list with the result of every command, in order.
Constraints
len(commands) == len(command_args)- Up to about 10^4 commands; each path is up to about 10^3 characters.
- All values and path segments are strings; values may be empty.
- Aim for time proportional to the path length per command.
Examples
Example 1
Input: replay_tree_store(['create', 'create', 'get_value', 'create', 'delete', 'set_value', 'get_value', 'delete', 'get_value', 'delete'], [['/shop', 'store'], ['/shop/apple', 'red'], ['/shop/apple'], ['/shop/apple', 'blue'], ['/shop'], ['/shop/apple', 'green'], ['/shop/apple'], ['/shop/apple'], ['/shop/apple'], ['/shop']])
Output: [True, True, 'red', False, False, True, 'green', True, None, True]
Hints
Hint 1
Model the store as a tree where every node keeps its own value and a dictionary from segment name to child node.
Hint 2
Write one helper that validates a path and splits it into segments (an empty list for the root), and another that walks from the root and returns the node or None.
Hint 3
For create and delete, walk to the parent of the target. Create fails if the parent is missing or the name already exists; delete fails if the target is missing or still has children. Handle the root and wrong argument counts before touching the tree.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Represent the store as a trie keyed by path segments. Each node holds its value and a dictionary children mapping a segment name to a child node. The root starts with value "#".
Every command follows the same pattern:
- Check the argument count; if wrong, return the command's failure result.
- Validate and split the path into segments. The root is the empty list; invalid paths yield
None. - Walk from the root one segment at a time.
- Act on the target node, or on its parent for
createanddelete.
Per command:
- create: reject invalid paths and the root. Walk to the parent. Fail if it is missing or already has a child with that name. Otherwise insert a new node.
- set_value: walk to the node; fail if missing, otherwise overwrite its value.
- get_value: walk to the node; return its value or
None. - delete: reject invalid paths and the root. Walk to the parent, find the child, and fail if it is missing or has children. Otherwise remove it from the parent's dictionary.
- Unknown command names produce
None.
Why it is correct
A node exists exactly when it is reachable from the root by its segments. create only attaches under an existing parent, and delete only removes leaves, so no subtree is ever orphaned. All validation happens before any mutation, so a failed command leaves the store unchanged. Missing values are distinguished by None rather than falsiness, so the empty string is handled correctly.
Complexity
Let L be the length of a path. Each command costs O(L) for splitting and walking. Space is O(total size of the node segments and values stored). Each node stores only its own segment, not the full path.
An alternative is a flat hash map from path to value plus a child count, which is also O(L) per command, but the trie enforces the hierarchy structurally and extends easily to listing children.
Reference solution
from typing import List
def replay_tree_store(commands: List[str], command_args: List[List[str]]) -> List[object]:
root = {"value": "#", "children": {}}
def parse_path(path):
if not isinstance(path, str) or not path.startswith("/"):
return None
if path == "/":
return []
parts = path[1:].split("/")
if any(part in ("", ".", "..") for part in parts):
return None
return parts
def lookup(parts):
node = root
for part in parts:
node = node["children"].get(part)
if node is None:
return None
return node
results = []
for operation, args in zip(commands, command_args):
if operation == "create":
if len(args) != 2:
results.append(False)
continue
parts = parse_path(args[0])
if parts is None or not parts:
results.append(False)
continue
parent = lookup(parts[:-1])
name = parts[-1]
if parent is None or name in parent["children"]:
results.append(False)
continue
parent["children"][name] = {"value": args[1], "children": {}}
results.append(True)
elif operation == "set_value":
if len(args) != 2:
results.append(False)
continue
parts = parse_path(args[0])
node = lookup(parts) if parts is not None else None
if node is None:
results.append(False)
else:
node["value"] = args[1]
results.append(True)
elif operation == "get_value":
if len(args) != 1:
results.append(None)
continue
parts = parse_path(args[0])
node = lookup(parts) if parts is not None else None
results.append(node["value"] if node is not None else None)
elif operation == "delete":
if len(args) != 1:
results.append(False)
continue
parts = parse_path(args[0])
if parts is None or not parts:
results.append(False)
continue
parent = lookup(parts[:-1])
if parent is None:
results.append(False)
continue
node = parent["children"].get(parts[-1])
if node is None or node["children"]:
results.append(False)
else:
del parent["children"][parts[-1]]
results.append(True)
else:
results.append(None)
return results