Simulate a Tiny Hierarchical File Store from a Command Log
Data Structure DesignAuto-graded · 16 test casesLast updated
Replay a command log against an in-memory directory tree, with auto-created parent folders, file appends, reads and sorted listings.
Simulate a Tiny Hierarchical File Store from a Command Log
You are given a log of commands to replay against a file store that lives entirely in memory. The store is a tree of folders and files, rooted at /. Write a function that executes the commands in order and returns the result of each one.
Input
commands: a list of command names.command_args: a list of argument lists.command_args[i]holds the arguments forcommands[i].
Both lists have the same length.
Commands
| Command | Arguments | What it does | Result recorded |
|---|---|---|---|
"FileSystem" | none | Resets the store to a single empty root folder /. | None |
"mkdir" | [path] | Creates the folder at path. Any missing folders along the way are created too. If the folder already exists, nothing changes. | None |
"add_content_to_file" | [file_path, content] | If the file does not exist, creates it (and any missing parent folders) with content. If it already exists, appends content to the end of its current text. | None |
"read_content_from_file" | [file_path] | Reads the file's full text. | the text, as a string |
"ls" | [path] | If path is a file, lists just that file's own name. If path is a folder, lists the names of everything directly inside it. | a list of strings |
Listing rules
- For a file,
lsreturns a one-element list holding the last component of the path. - For a folder,
lsreturns the immediate children (files and sub-folders), sorted in ascending lexicographic (alphabetical) order. - Only direct children appear. Nothing nested deeper is included.
- An empty folder yields
[]. This includes the root of a fresh store.
Path rules
- Every path is absolute and starts with
/. It never ends with/, except for the root path/itself. - Each component is made of lowercase English letters.
- Two entries in the same folder never share a name. Entries in different folders may.
- An empty folder and a file whose text is empty are different things. Remember which entries are files, and do not infer it from their contents.
Output
Return a list with one entry per command, in the same order as commands. Use None for commands that produce no value.
You may assume that every command is valid. For example, you will never read a folder as if it were a file, and you will never list a path that does not exist.
Constraints
1 <= len(commands) == len(command_args) <= 500- Every path has length at most
100. - Path components consist only of lowercase letters
a-z. - Every
lsandread_content_from_filecommand targets an existing path of the appropriate kind. - The first command is
"FileSystem".
Examples
Example 1
Input: simulate_file_store(['FileSystem', 'ls', 'mkdir', 'add_content_to_file', 'ls', 'ls', 'ls', 'read_content_from_file', 'add_content_to_file', 'read_content_from_file'], [[], ['/'], ['/a/b/c'], ['/a/b/c/d', 'hello'], ['/'], ['/a/b'], ['/a/b/c/d'], ['/a/b/c/d'], ['/a/b/c/d', ' world'], ['/a/b/c/d']])
Output: [None, [], None, None, ['a'], ['c'], ['d'], 'hello', None, 'hello world']
Hints
Hint 1
Model the store as a tree. Each node needs a dictionary of children, a flag saying whether it is a file, and a text field. The flag is what separates an empty file from an empty folder.
Hint 2
Split each path on '/' and throw away empty pieces. The root path then becomes an empty list of components, so it needs no special case. One helper can walk the components, creating missing nodes when asked to.
Hint 3
Only 'ls' needs ordering, so keep children in a plain dict and sort the names when listing. For a file, return the last path component instead of children.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Represent the store as a tree keyed by path components. Each node has:
- a dictionary mapping child names to child nodes,
- an
is_fileflag, - the file text, kept as a list of chunks.
Every command starts the same way. Split the path on / and drop the empty pieces. Then walk down from the root one component at a time. The commands differ only in whether missing components are created or assumed to exist, so a single shared walking helper with a create option covers all of them.
FileSystem: replace the root with a fresh empty node.mkdir: walk with creation on. Existing folders are simply found again, so repeating amkdirchanges nothing.add_content_to_file: walk with creation on, mark the final node as a file, and append the new text. A new file starts with no chunks, and an existing file keeps its earlier text, so both cases take the same path.read_content_from_file: walk without creation and join the chunks.ls: walk without creation. If the node is a file, return the last path component. Otherwise return the sorted child names.
Why it is correct
- Splitting
"/"and discarding empty pieces gives an empty list, so the root resolves to the root node with no special case. It is never a file, so the "last component" lookup inlsnever runs on an empty list. - The explicit
is_fileflag keeps an empty file (lsreturns its name) distinct from an empty folder (lsreturns[]). - Names are stored per parent, so a file and a folder with the same name in different locations never collide.
- Children are sorted only when listed, so
lsalways returns them in lexicographic order. - Keeping text as chunks and joining on read preserves append order exactly.
Complexity
Let L be the path length, k the number of children in the listed folder, and C the size of the file text.
mkdir: O(L)add_content_to_file: O(L + len(content))read_content_from_file: O(L + C)ls: O(L + k log k)- Space: O(number of nodes + total stored text)
Reference solution
from typing import List
def simulate_file_store(commands: List[str], command_args: List[List[str]]) -> List[object]:
def make_node(is_file=False):
return {"children": {}, "is_file": is_file, "content": []}
root = make_node()
output = []
def split(path):
return [p for p in path.split("/") if p]
def descend(parts, create):
node = root
for p in parts:
if p not in node["children"]:
if not create:
raise KeyError(p)
node["children"][p] = make_node()
node = node["children"][p]
return node
for cmd, args in zip(commands, command_args):
if cmd == "FileSystem":
root = make_node()
output.append(None)
elif cmd == "ls":
parts = split(args[0])
node = descend(parts, False)
if node["is_file"]:
output.append([parts[-1]])
else:
output.append(sorted(node["children"]))
elif cmd == "mkdir":
descend(split(args[0]), True)
output.append(None)
elif cmd == "add_content_to_file":
file_path, content = args
node = descend(split(file_path), True)
node["is_file"] = True
node["content"].append(content)
output.append(None)
elif cmd == "read_content_from_file":
node = descend(split(args[0]), False)
output.append("".join(node["content"]))
else:
raise ValueError("Unknown command: " + cmd)
return output