Strict In-Memory Directory Tree and Shell Command Interpreter

Hard · Software Engineering Fundamentals · Software Engineer · Onsite

Problem Statement

Build an in-memory hierarchical file system rooted at "/" and expose a batch interpreter execute_commands that processes a list of shell-style command strings sequentially:

def execute_commands(commands: List[str]) -> List[object]:

Starting from an empty root directory "/", evaluate each string in commands in order and return a list of results of matching length. When a command fails, record {"error": "<message>"} at that index without halting subsequent commands.

Evaluation Order & Error Precedence

Validate every command in the exact sequence below and return the first matching error:

  1. Command verb & arity: Split the string on whitespace (command.split(), ignoring leading/trailing whitespace and collapsing consecutive spaces).
    • Supported verbs (case-sensitive): "mkdir", "touch", "ls", "rm", "rmdir".
    • Empty input or an unrecognized verb -> {"error": "unknown command"}.
    • Token count other than 2 -> {"error": "wrong number of arguments"}.
  2. Strict path syntax: Let path be the second token.
    • path must equal "/" or start with "/" followed by one or more non-empty component names separated by single "/" characters (trailing slashes like "/logs/" and repeated slashes like "//logs" are invalid).
    • Every component name may contain only ASCII letters (A-Z, a-z), digits (0-9), ., _, and -, and must not equal "." or ".." (other dot names such as ".env" or "..." are valid).
    • Any syntax violation -> {"error": "invalid path"}.
  3. Root protection:
    • Calling "mkdir", "touch", "rm", or "rmdir" on "/" -> {"error": "cannot modify root"}. ("ls /" is valid.)
  4. Ancestor traversal (no implicit parent creation):
    • Walk intermediate components components[:-1] starting from "/":
      • Missing intermediate component -> {"error": "parent directory does not exist"}.
      • Intermediate component is a file -> {"error": "not a directory"}.
  5. Target operation:
    • mkdir <path>: If the final component already exists in the parent directory (as a file or directory) -> {"error": "path already exists"}; otherwise create an empty directory and return True.
    • touch <path>: If the final component already exists in the parent directory (as a file or directory) -> {"error": "path already exists"}; otherwise create an empty file and return True.
    • ls <path>: On "/", inspect root; otherwise if the final component does not exist -> {"error": "path does not exist"}, or if it is a file -> {"error": "not a directory"}. Return a list of direct child names sorted in standard ASCII code-point order.
    • rm <path>: If the final component does not exist -> {"error": "path does not exist"}; if it is a directory -> {"error": "is a directory"}; otherwise delete the file and return True.
    • rmdir <path>: If the final component does not exist -> {"error": "path does not exist"}; if it is a file -> {"error": "not a directory"}; if the directory still contains any entries -> {"error": "directory not empty"}; otherwise delete the directory and return True.

Examples

Example 1

Input:
  commands = [
    "mkdir /logs",
    "touch /logs/app.log",
    "mkdir /logs/archive",
    "ls /logs",
    "rm /logs/app.log",
    "rmdir /logs/archive",
    "ls /logs"
  ]

Output: [True, True, True, ["app.log", "archive"], True, True, []]

Walk-through: - /logs is created, populated with file app.log and subdirectory archive, and listed in ASCII order (["app.log", "archive"]). - Deleting app.log via rm and empty subdirectory archive via rmdir leaves /logs empty ([]).

Example 2

Input:
  commands = [
    "ls /",
    "rmdir /",
    "touch /readme.txt",
    "ls /readme.txt",
    "rm /readme.txt/",
    "rm /readme.txt",
    "ls /"
  ]

Output: [
  [],
  {"error": "cannot modify root"},
  True,
  {"error": "not a directory"},
  {"error": "invalid path"},
  True,
  []
]

Walk-through: - "/" starts empty ([]) and rejects rmdir / with "cannot modify root". - ls rejects file /readme.txt with "not a directory", and rm /readme.txt/ fails path validation ("invalid path") because of the trailing slash before rm /readme.txt removes the file.

Example 3

Input:
  commands = [
    "mkdir /src/core",
    "mkdir /src",
    "touch /src/main.py",
    "mkdir /src/main.py",
    "rmdir /src",
    "ls /src"
  ]

Output: [
  {"error": "parent directory does not exist"},
  True,
  True,
  {"error": "path already exists"},
  {"error": "directory not empty"},
  ["main.py"]
]

Walk-through: - mkdir /src/core fails because /src does not exist yet. - Once /src and /src/main.py exist, mkdir /src/main.py fails with "path already exists", rmdir /src fails with "directory not empty", and ls /src still returns ["main.py"].

Constraints

  • 0 <= len(commands) <= 10^4
  • 0 <= len(commands[i]) <= 200
  • Total character length across all commands is at most 2 * 10^5.

Step-by-step walkthrough

  1. Understand the commands and error priority

    We need to implement execute_commands(commands), which runs a list of shell-style strings on a fresh in-memory file system starting with only the root directory /. Every command produces one item in the output list:

    • True when mkdir, touch, rm, or rmdir succeeds;
    • a sorted list of entry names (such as ["app.log", "archive"]) when ls succeeds;
    • {"error": message} when a command fails, while still continuing to execute the remaining commands.

    When a single command violates two rules at once—for example rm /missing/app.log or rm /readme.txt/—we must check conditions in a consistent order so the right error wins every time:

    Check order for every command:
    1. Command name known?                 -> else "unknown command"
    2. Exactly one path argument given?    -> else "wrong number of arguments"
    3. Path syntax strictly valid?         -> else "invalid path"
    4. Modifying "/" with mkdir/touch/rm/rmdir? -> "cannot modify root"
    5. Every ancestor directory exists?    -> else "parent directory does not exist"
                                              (or "not a directory" if an ancestor is a file)
    6. Final target check:
       - mkdir / touch: already exists?    -> "path already exists"
       - ls / rm / rmdir: missing?         -> "path does not exist"
       - ls / rmdir on a file?             -> "not a directory"
       - rm on a directory?                -> "is a directory"
       - rmdir on a non-empty directory?   -> "directory not empty"
    

    Notice two strict differences from everyday Unix shells: touch on an existing file is an error ("path already exists"), and ls on a file is an error ("not a directory").

  2. Model the file system as a tree of directories and files

    A tree is a hierarchy of nodes starting from a single root node (/), where each directory node holds named links to the files and subdirectories directly inside it.

    Why use a tree instead of a flat dictionary like {"/logs": "dir", "/logs/app.log": "file"}? With a flat dictionary, listing /logs or checking whether /logs is empty in rmdir /logs would have to scan every path stored in the entire file system. In a tree, each Directory keeps its own children dictionary mapping each immediate child's name to either a File or another Directory:

    root: Directory
      children = {
        "logs": Directory
                  children = {
                    "app.log": File(),
                    "archive": Directory(children={})
                  }
      }
    

    A File has no contents in this problem, so an empty class is enough—isinstance(node, Directory) cleanly distinguishes directories from files. We also define a custom FsError exception so any helper can abort immediately with a clear error message.

    class FsError(Exception):
        """Domain error raised when a file system rule fails; its text is the error message."""
    
    
    class File:
        """Represents an empty file node; its class distinguishes it from a Directory."""
    
    
    class Directory:
        def __init__(self) -> None:
            # children: maps entry name -> File or Directory, e.g. {"archive": Directory(), "app.log": File()}
            self.children: Dict[str, object] = {}
    
  3. Parse and strictly validate paths before touching the tree

    Before walking the tree, we convert the raw path string into a list of component names: "/" becomes [], and "/logs/archive" becomes ["logs", "archive"].

    To enforce strict path rules without a tangle of special cases, we check that path starts with "/" and then split path[1:] on "/" without stripping or filtering empty strings:

    path              path[1:].split("/")        why it passes or fails
    "/"               [] (handled up front)      valid root
    "/logs/archive"   ["logs", "archive"]        valid: every component uses allowed characters
    "/readme.txt/"    ["readme.txt", ""]         invalid: trailing slash produces ""
    "//logs"          ["", "logs"]               invalid: repeated slash produces ""
    "/logs/./app"     ["logs", ".", "app"]       invalid: "." and ".." are forbidden
    "logs/app"        (no leading "/")           invalid: relative path
    

    Because parse_path runs first in every method, malformed paths like rm /readme.txt/ fail with "invalid path" even when /readme.txt exists.

    # Allowed characters inside a single path component (letters, digits, '.', '_', '-').
    ALLOWED_NAME_CHARS = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-")
    
    
    def is_valid_name(name: str) -> bool:
        # Reject empty components (from "//" or trailing "/") and relative segments "." and "..".
        if name == "" or name == "." or name == "..":
            return False
        for ch in name:
            if ch not in ALLOWED_NAME_CHARS:
                return False
        return True
    
    
    def parse_path(path: str) -> List[str]:
        """Validate a strict absolute path and split it into component names ("/" -> [])."""
        if path == "/":
            return []
        if not path.startswith("/"):
            raise FsError("invalid path")
    
        # Do NOT strip slashes: "/a/" -> ["a", ""] and "//a" -> ["", "a"], so is_valid_name rejects them.
        names = path[1:].split("/")
        for name in names:
            if not is_valid_name(name):
                raise FsError("invalid path")
        return names
    
  4. Write one path walker for strict parent resolution

    Every operation after parse_path needs the same thing: find the parent Directory that holds the final component names[-1]. Writing one helper _parent_of(names) that walks names[:-1] from self.root solves two problems at once:

    1. It enforces the "no implicit parent creation" rule everywhere: if any ancestor is missing, it raises "parent directory does not exist".
    2. If an ancestor exists as a File (such as /readme.txt when accessing /readme.txt/sub), it raises "not a directory".

    For commands that require the final component to exist (ls, rm, rmdir), a tiny companion helper _existing_child(parent, target_name) looks up names[-1] and raises "path does not exist" if it is missing. That naturally separates ls /nope/x ("parent directory does not exist") from ls /nope ("path does not exist").

        def _parent_of(self, names: List[str]) -> Directory:
            """Walk names[:-1] from root without creating missing directories."""
            current = self.root
            for ancestor_name in names[:-1]:
                if ancestor_name not in current.children:
                    raise FsError("parent directory does not exist")
                next_node = current.children[ancestor_name]
                # Walking through a File (e.g. "/file/x") is always invalid.
                if not isinstance(next_node, Directory):
                    raise FsError("not a directory")
                current = next_node
            return current
    
        def _existing_child(self, parent: Directory, target_name: str) -> object:
            """Look up the final path component inside an already-resolved parent directory."""
            if target_name not in parent.children:
                raise FsError("path does not exist")
            return parent.children[target_name]
    
  5. Implement mkdir, touch, ls, rm, and rmdir

    Now each file system operation becomes a short, readable sequence of checks followed by a single dictionary read or write. Because every check runs before we mutate parent.children, a failed command never leaves partial changes behind:

    • mkdir and touch share _create_node: reject "/" (not names), walk to parent, verify target_name is not already in parent.children, and insert Directory() or File().
    • ls is the only command allowed on "/" (if not names: target = self.root). It verifies target is a Directory and returns sorted(target.children.keys()).
    • rm and rmdir both reject "/", resolve parent and target, verify the node's type (rm rejects directories; rmdir rejects files and non-empty directories), and delete parent.children[target_name].
        def _create_node(self, path: str, new_node: object) -> bool:
            """Shared creation flow for mkdir and touch so error priority stays identical."""
            names = parse_path(path)
            if not names:
                raise FsError("cannot modify root")
    
            parent = self._parent_of(names)
            target_name = names[-1]
            # Neither mkdir nor touch may overwrite an existing file or directory.
            if target_name in parent.children:
                raise FsError("path already exists")
    
            parent.children[target_name] = new_node
            return True
    
        def mkdir(self, path: str) -> bool:
            return self._create_node(path, Directory())
    
        def touch(self, path: str) -> bool:
            return self._create_node(path, File())
    
        def ls(self, path: str) -> List[str]:
            names = parse_path(path)
            # "/" is the one path with no parent directory; ls is allowed to inspect root directly.
            if not names:
                target = self.root
            else:
                parent = self._parent_of(names)
                target = self._existing_child(parent, names[-1])
    
            if not isinstance(target, Directory):
                raise FsError("not a directory")
            # Return a fresh list sorted in standard ASCII/lexicographical order.
            return sorted(target.children.keys())
    
        def rm(self, path: str) -> bool:
            names = parse_path(path)
            if not names:
                raise FsError("cannot modify root")
    
            parent = self._parent_of(names)
            target_name = names[-1]
            target = self._existing_child(parent, target_name)
            # rm deletes files only; directories must be removed with rmdir.
            if isinstance(target, Directory):
                raise FsError("is a directory")
    
            del parent.children[target_name]
            return True
    
        def rmdir(self, path: str) -> bool:
            names = parse_path(path)
            if not names:
                raise FsError("cannot modify root")
    
            parent = self._parent_of(names)
            target_name = names[-1]
            target = self._existing_child(parent, target_name)
            if not isinstance(target, Directory):
                raise FsError("not a directory")
            # Strict rmdir refuses to delete a directory that still holds any child entries.
            if target.children:
                raise FsError("directory not empty")
    
            del parent.children[target_name]
            return True
    
  6. Build a thin command dispatcher

    Separating command parsing from FileSystem makes debugging much cleaner: FileSystem only deals with validated paths and tree nodes, while run_command handles splitting the raw string and formatting error dictionaries.

    Using command.split() (with no separator argument) splits on any run of whitespace and trims leading/trailing spaces, so " mkdir /logs " cleanly becomes ["mkdir", "/logs"] while "" or " " becomes []. We catch only FsError—never bare Exception—so genuine coding mistakes still raise normal Python tracebacks during testing.

    def run_command(fs: FileSystem, command: str) -> object:
        """Parse one raw command string, invoke the matching FileSystem method, and format errors."""
        # handlers: maps command keyword -> bound FileSystem method taking one path string
        handlers = {
            "mkdir": fs.mkdir,
            "touch": fs.touch,
            "ls": fs.ls,
            "rm": fs.rm,
            "rmdir": fs.rmdir,
        }
        # split() with no arguments collapses repeated spaces and trims leading/trailing whitespace.
        words = command.split()
        if not words or words[0] not in handlers:
            return {"error": "unknown command"}
        if len(words) != 2:
            return {"error": "wrong number of arguments"}
    
        op_name, path_arg = words[0], words[1]
        try:
            return handlers[op_name](path_arg)
        except FsError as error:
            # Catch only FsError so unexpected bugs still surface as real tracebacks during debugging.
            return {"error": str(error)}
    
    
    def execute_commands(commands: List[str]) -> List[object]:
        fs = FileSystem()
        results: List[object] = []
        # Failed commands report {"error": ...} without aborting subsequent commands.
        for command in commands:
            results.append(run_command(fs, command))
        return results
    
  7. Trace Example 3 step by step

    Let's trace ['mkdir /src/core', 'mkdir /src', 'touch /src/main.py', 'mkdir /src/main.py', 'rmdir /src', 'ls /src']:

    #  command             names               tree walkthrough                                    output
    1  mkdir /src/core     ["src", "core"]     _parent_of checks "src" in /: missing               {"error": "parent directory does not exist"}
    2  mkdir /src          ["src"]             parent is /; "src" added as Directory()             True
    3  touch /src/main.py  ["src", "main.py"]  parent is /src; "main.py" added as File()           True
    4  mkdir /src/main.py  ["src", "main.py"]  parent is /src; "main.py" already in /src.children  {"error": "path already exists"}
    5  rmdir /src          ["src"]             target /src is a Directory with {"main.py": ...}    {"error": "directory not empty"}
    6  ls /src             ["src"]             target /src is a Directory -> sorted(["main.py"])   ["main.py"]
    

    Notice how commands 1, 4, and 5 fail cleanly without corrupting the tree or halting command 6.

  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    # Allowed characters inside a single path component (letters, digits, '.', '_', '-').
    ALLOWED_NAME_CHARS = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-")
    
    
    class FsError(Exception):
        """Domain error raised when a file system rule fails; its text is the error message."""
    
    
    class File:
        """Represents an empty file node; its class distinguishes it from a Directory."""
    
    
    class Directory:
        def __init__(self) -> None:
            # children: maps entry name -> File or Directory, e.g. {"archive": Directory(), "app.log": File()}
            self.children: Dict[str, object] = {}
    
    
    def is_valid_name(name: str) -> bool:
        # Reject empty components (from "//" or trailing "/") and relative segments "." and "..".
        if name == "" or name == "." or name == "..":
            return False
        for ch in name:
            if ch not in ALLOWED_NAME_CHARS:
                return False
        return True
    
    
    def parse_path(path: str) -> List[str]:
        """Validate a strict absolute path and split it into component names ("/" -> [])."""
        if path == "/":
            return []
        if not path.startswith("/"):
            raise FsError("invalid path")
    
        # Do NOT strip slashes: "/a/" -> ["a", ""] and "//a" -> ["", "a"], so is_valid_name rejects them.
        names = path[1:].split("/")
        for name in names:
            if not is_valid_name(name):
                raise FsError("invalid path")
        return names
    
    
    class FileSystem:
        def __init__(self) -> None:
            # root: single top-level Directory representing "/"
            self.root = Directory()
    
        def _parent_of(self, names: List[str]) -> Directory:
            """Walk names[:-1] from root without creating missing directories."""
            current = self.root
            for ancestor_name in names[:-1]:
                if ancestor_name not in current.children:
                    raise FsError("parent directory does not exist")
                next_node = current.children[ancestor_name]
                # Walking through a File (e.g. "/file/x") is always invalid.
                if not isinstance(next_node, Directory):
                    raise FsError("not a directory")
                current = next_node
            return current
    
        def _existing_child(self, parent: Directory, target_name: str) -> object:
            """Look up the final path component inside an already-resolved parent directory."""
            if target_name not in parent.children:
                raise FsError("path does not exist")
            return parent.children[target_name]
    
        def _create_node(self, path: str, new_node: object) -> bool:
            """Shared creation flow for mkdir and touch so error priority stays identical."""
            names = parse_path(path)
            if not names:
                raise FsError("cannot modify root")
    
            parent = self._parent_of(names)
            target_name = names[-1]
            # Neither mkdir nor touch may overwrite an existing file or directory.
            if target_name in parent.children:
                raise FsError("path already exists")
    
            parent.children[target_name] = new_node
            return True
    
        def mkdir(self, path: str) -> bool:
            return self._create_node(path, Directory())
    
        def touch(self, path: str) -> bool:
            return self._create_node(path, File())
    
        def ls(self, path: str) -> List[str]:
            names = parse_path(path)
            # "/" is the one path with no parent directory; ls is allowed to inspect root directly.
            if not names:
                target = self.root
            else:
                parent = self._parent_of(names)
                target = self._existing_child(parent, names[-1])
    
            if not isinstance(target, Directory):
                raise FsError("not a directory")
            # Return a fresh list sorted in standard ASCII/lexicographical order.
            return sorted(target.children.keys())
    
        def rm(self, path: str) -> bool:
            names = parse_path(path)
            if not names:
                raise FsError("cannot modify root")
    
            parent = self._parent_of(names)
            target_name = names[-1]
            target = self._existing_child(parent, target_name)
            # rm deletes files only; directories must be removed with rmdir.
            if isinstance(target, Directory):
                raise FsError("is a directory")
    
            del parent.children[target_name]
            return True
    
        def rmdir(self, path: str) -> bool:
            names = parse_path(path)
            if not names:
                raise FsError("cannot modify root")
    
            parent = self._parent_of(names)
            target_name = names[-1]
            target = self._existing_child(parent, target_name)
            if not isinstance(target, Directory):
                raise FsError("not a directory")
            # Strict rmdir refuses to delete a directory that still holds any child entries.
            if target.children:
                raise FsError("directory not empty")
    
            del parent.children[target_name]
            return True
    
    
    def run_command(fs: FileSystem, command: str) -> object:
        """Parse one raw command string, invoke the matching FileSystem method, and format errors."""
        # handlers: maps command keyword -> bound FileSystem method taking one path string
        handlers = {
            "mkdir": fs.mkdir,
            "touch": fs.touch,
            "ls": fs.ls,
            "rm": fs.rm,
            "rmdir": fs.rmdir,
        }
        # split() with no arguments collapses repeated spaces and trims leading/trailing whitespace.
        words = command.split()
        if not words or words[0] not in handlers:
            return {"error": "unknown command"}
        if len(words) != 2:
            return {"error": "wrong number of arguments"}
    
        op_name, path_arg = words[0], words[1]
        try:
            return handlers[op_name](path_arg)
        except FsError as error:
            # Catch only FsError so unexpected bugs still surface as real tracebacks during debugging.
            return {"error": str(error)}
    
    
    def execute_commands(commands: List[str]) -> List[object]:
        fs = FileSystem()
        results: List[object] = []
        # Failed commands report {"error": ...} without aborting subsequent commands.
        for command in commands:
            results.append(run_command(fs, command))
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture a set of nested filing folders starting from one master folder labeled /. Inside each folder is an index card (a Python dictionary) that maps each item's name either to another folder (Directory) or to a blank sheet (File). This hierarchy of folders and files is a tree—a structure starting at one root node where every directory node stores named links to its immediate children. Every command follows the same two-part routine: first walk step by step from / down to the parent folder, and then inspect, add, or delete the final name on that parent folder's index card.

A tempting shortcut is to store every path in one flat dictionary like {"/logs": "dir", "/logs/app.log": "file"} instead of building a tree. That falls short as the file system grows: ls /logs and the emptiness check in rmdir /logs would have to scan every path in the entire file system in O(N) time just to see whether anything starts with "/logs/". Likewise, slicing strings separately inside each command duplicates path validation and easily mixes up error priorities (for example reporting "path does not exist" on rm /missing/app.log when "parent directory does not exist" is required). Putting path validation in one parser, ancestor traversal in one walker (_parent_of), and string splitting in a dispatcher (a thin routing function that maps a command word to its method and formats the output) keeps every rule in one place.

Here is a quick trace of 5 commands starting from an empty root /:

  1. mkdir /logs -> parse_path yields ["logs"]; parent is /, which does not have "logs" yet, so / gets "logs": Directory() and returns True.
  2. touch /logs/app.log -> parse_path yields ["logs", "app.log"]; _parent_of steps into /logs, sees "app.log" is free, inserts "app.log": File(), and returns True.
  3. rmdir /logs -> target /logs is a Directory, but its children dictionary still contains "app.log", so it fails with {"error": "directory not empty"}.
  4. rm /logs/app.log -> walks into /logs, confirms "app.log" is a File, deletes "app.log" from /logs.children, and returns True.
  5. rmdir /logs -> /logs.children is now empty, so "logs" is deleted from root.children and returns True.

Complexity

Let L be the character length of a single command string, c be the number of entries inside the directory that ls lists, and M be the maximum length of an entry name in that directory.

  • Time per mkdir, touch, rm, or rmdir: O(L). Splitting and validating the command and path inspects each character a constant number of times, and walking the path performs one O(1)-average dictionary lookup per component name (whose lengths sum to less than L).
  • Time per ls: O(L + M * c log c) (which is O(L + c log c) when entry names have bounded length). Walking to the directory takes O(L) time, and sorting its c child names in lexicographical order (character-by-character comparison by numeric ASCII code) performs O(c log c) string comparisons of up to M characters each.
  • Space: O(N + S) for the file system tree, where N is the number of live files and directories and S is the total characters in their stored names, plus the output list returned by execute_commands (one result per command, with O(c) references per ls call).

Edge cases

  • Root directory /: ls / succeeds even when the file system is empty ([]), whereas mkdir /, touch /, rm /, and rmdir / all fail with "cannot modify root" regardless of whether / has children.
  • Strict path syntax: relative paths (logs/app), trailing slashes (/readme.txt/), repeated slashes (//logs, /logs//app), and dot segments (/., /.., /logs/../logs) all fail immediately with "invalid path"—even if /readme.txt or /logs exists—because parse_path runs before any tree lookup.
  • Dots inside ordinary names: only the exact component names "." and ".." are forbidden, so names like ".hidden" and "..." are valid, and ASCII sorting places "." before digits, digits before uppercase letters, "_" between uppercase and lowercase, and "a10" before "a2".
  • Missing ancestor vs missing target: ls /nope/x fails during _parent_of with "parent directory does not exist", whereas ls /nope reaches / and fails in _existing_child with "path does not exist".
  • File along the path: any command whose path passes through a file (such as mkdir /f/x or ls /f/x when /f is a file) fails with "not a directory".
  • Reusing deleted names: once rm /logs/app.log removes a file, mkdir /logs/app.log can reuse that name for a directory (and vice versa after rmdir), and a recreated directory always starts empty.
  • Malformed commands: empty strings, whitespace-only strings, unknown verbs (cat /logs), and uppercase verbs (MKDIR /logs) return "unknown command"; missing or extra arguments (ls, mkdir /a /b) return "wrong number of arguments", and execution continues to the next command.

Common mistakes

  • Cleaning paths instead of rejecting bad ones. Calling path.strip("/") or filtering out empty segments after split("/") silently accepts "/readme.txt/" and "//logs" instead of returning "invalid path".
  • Implicitly creating parent directories. Auto-creating missing folders mkdir -p style breaks strict validation (mkdir /src/core must fail when /src does not exist).
  • Checking the final name before checking ancestors. In a flat-map design, checking if path not in kind first makes rm /nope/x return "path does not exist" instead of "parent directory does not exist".
  • Treating touch on an existing file as a no-op or ls on a file as [filename]. Standard Unix shells behave that way, but these strict specifications require "path already exists" and "not a directory".
  • Returning list(target.children.keys()) without sorted(...). Python dictionaries preserve insertion order, which happens to pass Example 1 (app.log created before archive) by coincidence while failing whenever entries are created out of alphabetical order.
  • Catching bare Exception in run_command. Wrapping the call in except Exception turns typos like NameError or AttributeError into {"error": ...} dictionaries, making bugs much harder to diagnose than catching only FsError.
  • Using command.split(" ") instead of command.split(). Splitting on a single space turns " mkdir /logs " into empty-string tokens and wrongly triggers "wrong number of arguments".

Alternative approaches

  • Flat dictionary from absolute path to node kind ({"/": "dir", "/logs": "dir"}). Easy to write for tiny inputs (and handy as a brute-force reference oracle in tests), but ls and rmdir's emptiness check must scan all N paths in O(N) time unless you also maintain a second parent-to-children map—at which point you are maintaining a tree anyway.
  • Returning (result, error) tuples instead of raising FsError. Avoids exceptions for expected user errors, at the cost of checking if error is not None: after every helper call (parse_path, _parent_of, _existing_child). Raising one dedicated FsError and catching it at the run_command boundary keeps each method linear and readable.

Follow-up questions

  • How could you support recursive parent creation (mkdir -p) and subtree deletion (rm -r) while reusing the existing traversal logic? Add an optional boolean parameter create_missing: bool = False to _parent_of: whenever ancestor_name is missing and create_missing is True, insert current.children[ancestor_name] = Directory() and keep walking (an existing File along the path still raises "not a directory"). mkdir -p then calls _parent_of(names, create_missing=True) and treats an existing Directory at names[-1] as True (while still failing if names[-1] is a File). For recursive deletion (rm -r), parse the path, reject "/", use the exact same _parent_of and _existing_child helpers, and simply del parent.children[target_name] without rejecting non-empty directories—detaching that one reference drops the entire subtree (the node and all descendants nested beneath it).

  • What changes are needed to store file payloads (write / cat) and relocate an entire directory branch via mv? Add self.content: str = "" to File: write(path, text) walks to the parent, creates a File if missing or overwrites target.content if it is already a File (failing on a Directory), and cat(path) walks to an existing File and returns target.content. For mv(src, dst), validate both paths, reject "/" for either argument, resolve both parent directories, and verify three conditions: src exists, dst does not already exist, and dst is not inside src (checked cleanly on parsed component lists: dst_names[:len(src_names)] == src_names), which prevents detaching a directory into a cycle inside itself. Then node = src_parent.children.pop(src_names[-1]) and dst_parent.children[dst_names[-1]] = node moves an arbitrarily large subtree in O(L) time because child names live in the parent dictionary rather than as full paths on every descendant.

  • How would you make the file system safe under concurrent multi-threaded access, and what hazards arise during cross-directory mv? The simplest thread-safe design wraps each public method in a single coarse-grained mutex (a lock that allows only one thread at a time to execute protected code). For higher concurrency across separate branches, give each Directory its own lock (ideally a readers-writer lock, which allows multiple concurrent lookups while giving directory updates exclusive access) and traverse hand over hand (acquiring the child directory's lock before releasing the parent's lock). Cross-directory mv breaks naive per-directory locking in two ways: locking two parents in opposite orders across two concurrent moves causes a deadlock (two threads waiting forever on each other's locks), and concurrent mv /a /b/x + mv /b /a/y can both pass their local "not inside src" checks before either finishes, detaching both subtrees from /; following the Linux VFS pattern—acquiring one file-system-wide rename lock before any cross-directory mv, then locking the two parents in deterministic order—prevents both bugs.

  • How would you keep ls responsive when a single directory holds millions of entries that must be returned in sorted order? Instead of sorting target.children from scratch in O(c log c) on every ls, maintain child names in sorted order alongside the hash map as entries are created and removed—using a balanced binary search tree or skip list (ordered structures that keep keys sorted while supporting search, insertion, and deletion in O(log c) time). That turns mkdir/touch/rm/rmdir into O(L + log c) and lets ls iterate already-sorted names in O(c) time. When c is in the millions, also add cursor pagination (accepting after_name and limit parameters so each call binary-searches to after_name and returns only the next k names in O(L + log c + k) time instead of copying millions of strings at once).

Follow-up questions

Similar questions

More Perplexity interview questions

All 13 Perplexity questions →