Design In-Memory File System

Free with account Updated Nov 19, 2026 · 8 min read
On this page

    Problem statement

    Build an in-memory file system that works with absolute paths such as /courses/system-design/cache.md. Support four operations. mkdir(path) creates the folder and any missing parent folders. addContentToFile(path, content) creates the file if needed (and its parent folders) and appends content. readContentFromFile(path) returns the file's full content. ls(path) returns the sorted names inside a folder, or, if path is a file, a list with just that file's name.

    Interviewers often run this as a progressive exercise: get the four basic calls working, then add delete, move, sizes, search or per-user limits on top of the same classes. Good structure at level 1 makes every later level easy. The level-1 version is LeetCode 588.

    Example

    Each call adds nodes to one tree; ls lists a folder's children in sorted order.
    Each call adds nodes to one tree; ls lists a folder's children in sorted order.
    ls("/")                                                  -> []
    mkdir("/courses/system-design")
    addContentToFile("/courses/system-design/cache.md", "hit")
    addContentToFile("/courses/system-design/cache.md", " or miss")
    addContentToFile("/courses/coding.md", "two pointers")
    ls("/")                                                  -> ["courses"]
    ls("/courses")                                           -> ["coding.md", "system-design"]
    ls("/courses/system-design/cache.md")                    -> ["cache.md"]
    readContentFromFile("/courses/system-design/cache.md")   -> "hit or miss"

    Constraints (assumed)

    • Paths are absolute, use / as the separator, and contain only lowercase letters, digits, . and -.
    • Up to 300 calls; a name is never used for both a file and a folder in the same place.
    • Reads and listings never ask about paths that don't exist.

    What this question tests

    • Choosing a tree of nodes (a trie keyed by path part) instead of a flat map of strings.
    • Clean helpers: one walk function used by every operation.
    • Telling files and folders apart, and designing classes you can extend in later levels.

    Questions to ask first

    1. Does mkdir create missing parents? (Here: yes, like mkdir -p.)
    2. Does writing to a file append or overwrite? (Here: append.)
    3. What should ls on a file return? (Here: a list with the file's own name.)
    4. How should errors behave: missing paths, a file used as a folder? (Here: they don't happen; in later levels, raise or return a status.)