Design In-Memory File System (LeetCode 588): Solution and Explanation

Hard
Hash Table
String
Design
Trie

Build a small file system in memory that supports listing a path, creating directories along a path, appending text to a file (creating it if needed) and reading a file back. Listing a directory returns its entries in lexicographic order, and listing a file returns just the file's name.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

A file system is a tree: every directory has named children, and files are leaves that hold content. Paths are just sequences of names from the root, which is exactly the shape of a trie keyed by path components instead of characters. So the design question is mostly about how to represent nodes and how to tell files apart from directories.

The reference solution keeps it very lean by using nested Python dictionaries. A directory is a dict mapping child names to child nodes, and a file is a plain str holding its content. Walking a path means splitting it on /, dropping the empty first piece, and stepping into the dictionary one name at a time. Whether we have reached a file or a directory is answered with isinstance(node, str).

Each operation follows from that. mkdir walks the path and creates any missing dictionaries along the way, which also handles nested creation like mkdir -p. addContentToFile does the same for all directories except the last name, then creates the file as an empty string if needed and appends the content. readContentFromFile walks to the leaf and returns the string. ls walks to the target; if it is a file, it returns a list containing only the file's name, otherwise the sorted names of the directory's children.

Approach: Trie of nested dictionaries

  1. Represent the root as an empty dict. Directories are dicts and files are strings.
  2. For ls(path), start at the root. Unless the path is /, split it and walk each component; if the final node is a string, return [parts[-1]].
  3. Otherwise return the sorted keys of the directory node.
  4. For mkdir(path), walk each component and create an empty dict wherever one is missing.
  5. For addContentToFile(filePath, content), create missing directories for all but the last component, create the file as an empty string if absent, then append content.
  6. For readContentFromFile(filePath), walk every component and return the string stored at the end.

Step-by-step example

ls("/"), mkdir("/a/b/c"), addContentToFile("/a/b/c/d", "hello"), ls("/"), ls("/a/b/c/d"), readContentFromFile("/a/b/c/d")
  1. ls("/") on an empty root returns [].
  2. mkdir("/a/b/c") splits into ["a", "b", "c"] and creates nested dicts, so the root becomes {"a": {"b": {"c": {}}}}.
  3. addContentToFile walks a, b and c, then creates "d" as "" and appends, so c holds {"d": "hello"}.
  4. ls("/") returns ["a"], the sorted keys of the root.
  5. ls("/a/b/c/d") lands on a string, so it returns ["d"]. readContentFromFile returns "hello".

Code: Python, Java, C++

1class FileSystem:
2    def __init__(self):
3        self.root = {}
4
5    def ls(self, path: str) -> List[str]:
6        node = self.root
7        if path != '/':
8            parts = path.split('/')[1:]
9            for part in parts:
10                node = node[part]
11            if isinstance(node, str):
12                return [parts[-1]]
13        return sorted(k for k in node if k)
14
15    def mkdir(self, path: str) -> None:
16        node = self.root
17        for part in path.split('/')[1:]:
18            if part not in node:
19                node[part] = {}
20            node = node[part]
21
22    def addContentToFile(self, filePath: str, content: str) -> None:
23        node = self.root
24        parts = filePath.split('/')[1:]
25        for part in parts[:-1]:
26            if part not in node:
27                node[part] = {}
28            node = node[part]
29        if parts[-1] not in node:
30            node[parts[-1]] = ''
31        node[parts[-1]] += content
32
33    def readContentFromFile(self, filePath: str) -> str:
34        node = self.root
35        for part in filePath.split('/')[1:]:
36            node = node[part]
37        return node

Time and space complexity

Time

O(L) per operation, plus O(m log m) for ls

Every operation splits and walks a path of length L with one dict lookup per component. Listing a directory with m entries also sorts them. Appending content costs time proportional to the file size because Python strings are immutable.

Space

O(T)

T is the total number of path components created plus the total length of file content stored.

Other approaches

Explicit node class with a sorted map (time O(L × log m) per operation, space O(T))

Define a node with an isFile flag, a content builder and a TreeMap of children (or std::map in C++). Children stay sorted, so ls returns them without sorting, and a StringBuilder makes appends amortized O(content). This is the more typical answer in Java and C++.

Common mistakes

  • Splitting "/" and walking an empty component, which tries to look up a key named "". Handle the root path as a special case.
  • Returning the file's full path from ls on a file. The expected output is only the file name.
  • Forgetting that addContentToFile must create missing parent directories as well as the file itself.
  • Replacing a file's content instead of appending to it on repeated calls.

Frequently asked questions

Why is a trie a good fit for an in-memory file system?

Paths are sequences of names, and a trie stores sequences with shared prefixes in one tree. Directories that share a parent share the same nodes, and each lookup walks one level per path component.

How do you tell a file from a directory in this design?

In the dictionary version a directory is a dict and a file is a string, so a type check decides it. With an explicit node class, a boolean flag or a non-null content field does the same job.

How would you keep ls fast for huge directories?

Store children in a sorted structure such as a TreeMap so listing is a traversal rather than a sort. Insertions then cost O(log m), but every ls avoids the O(m log m) sort.

How would you add delete or move operations?

Walk to the parent of the target and remove or reattach the child entry. Because each subtree hangs off a single key in its parent, deleting or moving a whole directory is one dictionary operation after the path walk.