Design In-Memory File System
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 appendscontent.readContentFromFile(path)returns the file's full content.ls(path)returns the sorted names inside a folder, or, ifpathis 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

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
- Does
mkdircreate missing parents? (Here: yes, likemkdir -p.) - Does writing to a file append or overwrite? (Here: append.)
- What should
lson a file return? (Here: a list with the file's own name.) - 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.)
Try it yourself first
You have the full problem. Sketch your answer, then sign up free to read the complete walkthrough.
- The complete design, flow by flow, with pictures
- Deep dives into the hard parts
- What mid, senior and staff candidates are expected to say
- Full company question lists
Free forever. No card needed.