Batch Runner for a Slash-Separated Key Store
Data Structure DesignAuto-graded · 21 test casesLast updated
Simulate a hierarchical key store from a batch of create/get commands, where a key can only be created once its parent key already exists.
Task
You are building a small in-memory store whose keys are slash-separated paths such as /a or /a/b/c. Each stored path holds one integer value.
Instead of a class, you receive a whole batch of commands and must process them in order, returning one result per command.
The store starts out empty except for the root path /. The root is considered to exist implicitly, but it never holds a value.
Commands
Each command has a name (from commands) and a list of arguments (the matching entry in params).
"create"with arguments[path, value]- Adds
pathto the store with the integervalueand returnsTrue. - Returns
False, and leaves the store unchanged, if:pathis"/", orpathhas already been created, or- the parent of
pathdoes not exist.
- The parent of a top-level path such as
/ais the root, which always exists. The parent of/a/bis/a, which must have been created earlier.
- Adds
"get"with arguments[path]- Returns the integer value stored at
path. - Returns
-1ifpathhas not been created. This includes"/", since the root holds no value.
- Returns the integer value stored at
Nothing is ever removed or modified once created, so a failed create never changes the original value.
Output
Return a list with one entry per command, in the same order:
TrueorFalsefor eachcreate,- an integer for each
get.
Constraints
commandsandparamshave the same length.- Every command name is either
"create"or"get". - Every path starts with
/, has no trailing slash (except the root path/itself), has no empty segments, and its segments consist only of lowercase letters. - Values passed to
createare integers. - Paths are compared as exact strings. Only a path that was successfully created counts as existing.
Examples
Example 1
Input: run_path_store(['create', 'get', 'create', 'get'], [['/a', 1], ['/a'], ['/a/b', 2], ['/a/b']])
Output: [True, 1, True, 2]
Example 2
Input: run_path_store(['create', 'create', 'get'], [['/a/b', 2], ['/a', 1], ['/a/b']])
Output: [False, True, -1]
Example 3
Input: run_path_store(['create', 'create', 'get', 'get'], [['/leet', 10], ['/leet/code', 20], ['/leet'], ['/leet/code']])
Output: [True, True, 10, 20]
Hints
Hint 1
Think about what must be true of a path's parent before you may add the path. How do you obtain the parent string from the path?
Hint 2
A dictionary keyed by the full path string is enough to answer both 'does this exist' and 'what is its value' in one lookup.
Hint 3
Treat the root as a special case: it is always a valid parent, but it can never be created and never returns a value, so `get('/')` yields -1.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep a dictionary that maps each successfully created full path to its value, and walk through the commands in order.
create(path, value)
- If
pathis"/"or is already in the dictionary, the command fails. - Compute the parent by cutting the path at its last
/. For a top-level path like/athis gives an empty string, which we interpret as the root/. - If the parent is not the root and is not in the dictionary, the command fails.
- Otherwise store the value and report success.
get(path)
Look the path up in the dictionary and fall back to -1. The root is never stored, so get("/") naturally gives -1.
Why it is correct
The dictionary holds exactly the paths that were created successfully. A path is inserted only when its parent is the root or is already in the dictionary. Therefore, at every moment, every stored path has all of its ancestors stored too, which is precisely the "parent must exist" rule. Refusing to insert a path that is already present enforces "creating an existing path fails" and keeps the first value. Lookups succeed exactly for stored paths, so get returns -1 for everything else, including the root.
For example, creating /a/b before /a fails because /a is missing. After /a is created, /a/b can be created, but the earlier failed attempt left no trace, so a later get("/a/b") returns -1 until a create succeeds.
Complexity
Let L be the length of a path. Each command does a constant number of string operations and dictionary lookups, so it costs O(L). With n commands, total time is O(sum of path lengths). Space is O(total length of created paths).
A trie of segments gives the same bounds and is preferable if you later need subtree operations (deleting a subtree, wildcard lookups), but a flat dictionary is enough for this task.
Reference solution
from typing import Dict, List
def run_path_store(commands: List[str], params: List[List[object]]) -> List[object]:
store: Dict[str, int] = {}
results: List[object] = []
for command, args in zip(commands, params):
if command == "create":
path, value = args
path = str(path)
value = int(value)
if path == "/" or path in store:
results.append(False)
continue
parent = path.rsplit("/", 1)[0] or "/"
if parent != "/" and parent not in store:
results.append(False)
continue
store[path] = value
results.append(True)
elif command == "get":
path = str(args[0])
results.append(store.get(path, -1))
else:
raise ValueError(f"unknown operation: {command}")
return results