Batch-Driven Slash-Path Registry with Leaf-Only Deletion
Data Structure DesignAuto-graded · 21 test casesLast updated
Simulate a tree-shaped registry addressed by slash-separated paths, processing a batch of create, set, get and remove commands and returning one result per command.
You are building an in-memory registry whose entries are addressed by UNIX-style absolute paths such as /a/b. Entries form a tree: each entry can have child entries, and each entry stores one value.
Implement a function that processes a batch of commands, in order, against a single registry that starts fresh, and returns one result per command.
Commands
Command i is operations[i] and its parameters are arguments[i].
| Command | Parameters | Effect | Result |
|---|---|---|---|
"create" | [path, value] | Add a new entry at path holding value. Succeeds only if the parent entry exists and path itself does not exist yet. | true on success, otherwise false |
"set" | [path, value] | Replace the value of an existing entry. | true on success, false if the path does not exist |
"get" | [path] | Look up the value at path. | [true, value] if it exists, otherwise [false, null] |
"remove" | [path] | Delete the entry at path, but only if it exists and has no children. | true on success, otherwise false |
Any command name other than the four above produces false.
Path rules
- A valid path is a string that begins with
/. - The path
"/"is valid and denotes the root. - Any other valid path is
/followed by one or more segments separated by single/characters, and every segment must be non-empty. So"","a","/a/","//a"and"/a//b"are all malformed. - A non-string path is malformed.
- Segments are ordinary names;
.and..have no special meaning and no normalization is performed. - A malformed path makes the command fail (
falseforcreate,set,remove;[false, null]forget) and never changes the registry.
Root behavior
- The root entry always exists from the start, with initial value
null. get("/")therefore returns[true, <current root value>].set("/", v)succeeds and storesvat the root.create("/", ...)fails, since the root already exists.remove("/")always fails.
Other details
- A stored value may be
null.geton such an entry returns[true, null], which differs from the[false, null]returned for a missing path. - A failed
createmust leave the existing value untouched. - After a successful
remove, the same path may be created again. - If
createorsetarrives without a value argument, treat the value asnull. If a command has no path argument at all, treat its path as malformed.
Task
Return a list of results, one per command, in the same order as the commands.
Constraints
len(operations) == len(arguments)- Paths are limited in length only by reasonable input sizes; aim for time proportional to the path length per command.
- Values can be any JSON-like data (numbers, strings,
null, and so on). - Segment names are case-sensitive and compared exactly.
Examples
Example 1
Input: run_path_registry(['create', 'create', 'get', 'set', 'get', 'remove', 'get'], [['/a', 1], ['/a', 2], ['/a'], ['/a', 3], ['/a'], ['/a'], ['/a']])
Output: [True, False, [True, 1], True, [True, 3], True, [False, None]]
Example 2
Input: run_path_registry(['create', 'create', 'create', 'remove', 'remove', 'get'], [['/missing/child', 1], ['/a', 1], ['/a/b', 2], ['/a'], ['/a/b'], ['/a']])
Output: [False, True, True, False, True, [True, 1]]
Example 3
Input: run_path_registry(['get', 'set', 'get', 'create', 'get', 'remove', 'get'], [['/'], ['/', 7], ['/'], ['/', 9], ['//bad'], ['/'], ['/']])
Output: [[True, None], True, [True, 7], False, [False, None], False, [True, 7]]
Hints
Hint 1
Model the registry as a tree where every node holds a value and a dictionary from segment name to child node. The path `/a/b` is root, then child `a`, then child `b`.
Hint 2
Write one helper that validates and splits a path into segments (returning a failure marker for malformed input, and an empty list for the root), and another that walks the tree along a list of segments and returns the node or nothing.
Hint 3
For `create` and `remove`, walk to the parent using every segment except the last, then check the last segment in the parent's children. Handle the root specially: it can be read and set but never created or removed. Remember that `get` must return a found flag so a stored `null` is distinguishable from a miss.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Represent the registry as a tree (a trie keyed by path segments). Each node stores its value and a dictionary children mapping a segment name to a child node. The path /a/b corresponds to root, then child a, then child b.
Every command follows the same pattern:
- Parse the path. A valid path starts with
/;"/"becomes an empty segment list, and anything else is split on/after the leading slash. If any segment is empty, or the path is not a string, it is malformed. - Walk the tree, either to the target node or to its parent.
- Check the precondition and mutate:
create: the parent must exist and the last segment must not already be a child.set: the node must exist.get: return[True, value]if the node exists, else[False, None].remove: the node must exist and have no children.
Special cases: the root is created up front with value None. create("/") and remove("/") always fail, while get("/") and set("/", v) work normally. Unknown commands return False.
get returns a pair rather than just the value because None is a legal stored value, so a found flag is needed to tell "absent" apart from "present with None".
Why it is correct
The invariant is: a node exists in the tree exactly when its path was successfully created and not removed since.
createonly attaches a child to an existing parent and refuses duplicates, so every node's ancestors always exist and existing values are never overwritten.removeonly deletes childless nodes, so it never orphans a subtree.setandgetare pure lookups, which find a node exactly when every segment on the path exists, matching "the path exists" by the invariant.- Malformed paths are rejected before any traversal, so they cannot change state.
Complexity
Let L be the length of a path string. Each command costs O(L) time: splitting is linear, and the walk performs one dictionary lookup per segment with total hashing bounded by L. Extra space per command is O(L) for the segment list. Overall storage is proportional to the number of nodes plus the total characters in segment names.
Reference solution
from typing import List
def run_path_registry(operations: List[str], arguments: List[List[object]]) -> List[object]:
root = {"value": None, "children": {}}
results = []
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 == "" for part in parts):
return None
return parts
def find_node(parts):
node = root
for part in parts:
node = node["children"].get(part)
if node is None:
return None
return node
for operation, args in zip(operations, arguments):
path = args[0] if args else None
parts = parse_path(path)
if operation == "get":
node = find_node(parts) if parts is not None else None
results.append([node is not None, node["value"] if node is not None else None])
elif operation in ("create", "set"):
value = args[1] if len(args) > 1 else None
if parts is None:
results.append(False)
continue
if operation == "create":
if not parts:
results.append(False)
continue
parent = find_node(parts[:-1])
name = parts[-1]
if parent is None or name in parent["children"]:
results.append(False)
else:
parent["children"][name] = {"value": value, "children": {}}
results.append(True)
else:
node = find_node(parts)
if node is None:
results.append(False)
else:
node["value"] = value
results.append(True)
elif operation == "remove":
if parts is None or not parts:
results.append(False)
continue
parent = find_node(parts[:-1])
name = parts[-1]
node = parent["children"].get(name) if parent is not None else None
if node is None or node["children"]:
results.append(False)
else:
del parent["children"][name]
results.append(True)
else:
results.append(False)
return results