Replay Path Insertions and Filename Lookups on a Component Trie
Data Structure DesignAuto-graded · 23 test casesLast updated
Simulate an in-memory path trie driven by a list of add and search operations, with iterative traversal, path normalization, and exact rules for what counts as a file.
Replaying Operations on a Path Tree
You are given a script of operations to run against an initially empty, in-memory directory tree. Return what each operation produces.
Write a function that takes two parallel lists:
operations: strings, each either"add_path"or"find_file".arguments: for each operation, a list holding exactly one string, which is the argument to that operation.
Run the operations in order, starting from an empty tree. Pair the i-th operation with the i-th argument list. If the two lists have different lengths, process only as many pairs as the shorter list provides and ignore the rest.
Operations
add_path(path)
- Split the path on
/and discard every empty piece. This makes leading, repeated, and trailing slashes irrelevant. For example,//a//b/is the same as/a/b, and a string with no leading slash is split the same way. - Walk from the root through the resulting components in order, creating any component that does not yet exist.
- Mark the final node reached as a file. Adding the same path again changes nothing.
- If the path has no components (for example
"/"), nothing is marked, because the root is never a file.
find_file(filename)
Return the full absolute paths of every node that satisfies both conditions:
- It was marked as a file by some earlier
add_path. - Its last component equals
filenameexactly.
Rules for the result:
- Directories that were only created implicitly as parents are not files. They are never returned, even if their name matches.
- A node stays a file even if a longer path is added below it later. For example, after adding
/a/band then/a/b/c, searching forbreturns/a/b. - Each returned path is
/followed by its components joined with/. It has no trailing slash and no repeated slashes. - Sort the result with ordinary string comparison, character by character. Note that
"/a/b/a/t"comes before"/a/t"because'b' < 't'. - If nothing matches, return an empty list.
Output
Return a list with one entry per processed operation:
Nonefor eachadd_path.- The sorted list of path strings for each
find_file.
Paths can be nested up to 2000 levels deep, so the search should not rely on recursion. Use an explicit stack.
Constraints
- Paths contain lowercase letters, digits,
.and/. - At most
10^4add_pathoperations. - Every path has at most
2000components and at most10^5characters. - Every operation name is
"add_path"or"find_file". - Each argument list contains exactly one string.
Examples
Example 1
Input: run_path_tree_ops(['add_path', 'add_path', 'add_path', 'find_file', 'find_file', 'find_file'], [['/var/log/syslog'], ['/var/log/nginx/access.log'], ['/home/user/log/syslog'], ['syslog'], ['access.log'], ['missing.txt']])
Output: [None, None, None, ['/home/user/log/syslog', '/var/log/syslog'], ['/var/log/nginx/access.log'], []]
Example 2
Input: run_path_tree_ops(['add_path', 'add_path', 'find_file'], [['/a/b/a/target.txt'], ['/a/target.txt'], ['target.txt']])
Output: [None, None, ['/a/b/a/target.txt', '/a/target.txt']]
Example 3
Input: run_path_tree_ops(['add_path', 'add_path', 'add_path', 'find_file'], [['/file.txt'], ['//a//file.txt/'], ['file.txt']])
Output: [None, None, None]
Hints
Hint 1
Model the tree as a trie keyed by path component, where each node has a dictionary of children and a boolean saying whether a path ended exactly there.
Hint 2
Splitting on '/' and dropping empty strings handles leading, repeated and trailing slashes in one step, and gives an empty component list for '/'.
Hint 3
For lookup, push (node, components_so_far) onto an explicit stack, check the flag and last component when popping, and sort the collected strings at the end. Remember that zip-style pairing ignores extra operations or arguments.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Build a trie whose edges are path components rather than characters. Each node stores:
children: a dictionary from component name to child node.is_file: whether someadd_pathcall ended exactly at this node.
Insertion. Split the path on / and drop empty strings. This normalizes leading, repeated, and trailing slashes. Walk down from the root, creating missing children, and set is_file on the last node. A path with no components marks nothing, so the root is never a file. Re-adding a path just sets an already-true flag.
Search. Run a depth-first traversal with an explicit stack of (node, components) pairs, starting at (root, []). When a node is popped:
- If
is_fileis true and its last component equalsfilename, record'/' + '/'.join(components). - Push every child with its name appended to the component list.
Finally, sort the collected strings.
Replay. Iterate with zip(operations, arguments), which also gives the required "stop at the shorter list" behavior. Append None for each add and the search result for each find.
Why it is correct
- Each node is pushed only by its unique parent, so every node is visited exactly once and none is duplicated.
- The component list carried with a node is exactly its root-to-node path, since one name is appended per edge.
- The match test requires an explicit insertion plus a last-component match. Implicit directories are therefore excluded, and a node that later gains children stays a file.
- Equal names at different depths are different node objects reached by different routes, so they never collide.
- The final sort fixes the output order regardless of stack or dictionary order.
- The stack lives on the heap, so a chain 2000 levels deep cannot cause a recursion-limit failure.
Complexity
Let L be the length of a path, N the number of nodes, D the maximum depth, and m the number of matches.
add_path: O(L) time, and O(new components) extra space.find_file: each push copies the parent's component list, so the traversal costs O(N·D) time and the stack can hold O(N·D) elements in total. Sorting the matches adds O(m log m · D) time for comparisons.- Optional optimization: store a parent pointer in each node and rebuild a path only for matching nodes. This makes the traversal itself O(N).
Reference solution
from typing import List, Optional
class _Node:
def __init__(self):
self.children = {}
self.is_file = False
class _PathTree:
def __init__(self):
self.root = _Node()
def add(self, path: str) -> None:
parts = [p for p in path.split('/') if p]
node = self.root
for p in parts:
nxt = node.children.get(p)
if nxt is None:
nxt = _Node()
node.children[p] = nxt
node = nxt
if parts:
node.is_file = True
def find(self, filename: str) -> List[str]:
found = []
stack = [(self.root, [])]
while stack:
node, parts = stack.pop()
if node.is_file and parts and parts[-1] == filename:
found.append('/' + '/'.join(parts))
for name, child in node.children.items():
stack.append((child, parts + [name]))
found.sort()
return found
def run_path_tree_ops(operations: List[str], arguments: List[List[str]]) -> List[Optional[List[str]]]:
tree = _PathTree()
out = []
for op, args in zip(operations, arguments):
if op == 'add_path':
tree.add(args[0])
out.append(None)
elif op == 'find_file':
out.append(tree.find(args[0]))
else:
raise ValueError('unknown operation')
return out