772. Build an in-memory filesystem driven by shell-like commands
Coding agents are often given a sandboxed filesystem as a tool. Build a small in-memory version that understands a few shell-like commands.
Write run_fs(commands). Each command is a string. Paths are absolute, like /a/b/c.txt; the root / always exists. The commands are:
mkdir PATH creates the directory and any missing parents (fails if any part of the path is an existing file). write PATH TEXT sets the file content to TEXT (the rest of the line, which may contain spaces), creating the file if needed; the parent directory must already exist and PATH must not be a directory. cat PATH outputs the file content. ls PATH outputs the sorted names inside a directory joined by single spaces, with a trailing / on directory names (an empty directory outputs an empty string); ls on a file outputs just its name. rm PATH removes a file or an empty directory. rm -r PATH removes a file or a directory and everything in it; the root cannot be removed. mv SRC DST moves a file or directory to the new path DST; the parent of DST must exist, DST must not exist, and a directory cannot move inside itself.
Any command that fails outputs 'ERROR' and changes nothing. Return the list of outputs (only cat, ls and errors produce output).
def run_fs(commands)Example 1
Input: run_fs(['mkdir /a/b', 'write /a/note.txt hello world', 'ls /a', 'cat /a/note.txt'])
Output: ['b/ note.txt', 'hello world']
Constraints
- Up to 5,000 commands.
- Names contain no spaces or slashes.
Hint 1
Start with mkdir, write, cat and ls.
Hint 2
Write one path walker and reuse it everywhere.
Hint 3
Collect the edge cases for rm and mv before coding them.
Common mistakes
- Creating parent directories in mkdir before noticing a file blocks the path.
- Splitting the write text on spaces and losing repeated spaces.
- Allowing a directory to be moved into itself.
Understand the idea
Tree data structures with path resolution, and validate-then-mutate command handling.