Design In-Memory File System Problem
Description
LeetCode Problem 588.
Design a data structure that simulates an in-memory file system.
Implement the FileSystem class:
FileSystem()Initializes the object of the system.List<String> ls(String path)- If
pathis a file path, returns a list that only contains this file's name. - If
pathis a directory path, returns the list of file and directory names in this directory.
The answer should in lexicographic order.
- If
void mkdir(String path)Makes a new directory according to the givenpath. The given directory path does not exist. If the middle directories in the path do not exist, you should create them as well.void addContentToFile(String filePath, String content)- If
filePathdoes not exist, creates that file containing givencontent. - If
filePathalready exists, appends the givencontentto original content.
- If
String readContentFromFile(String filePath)Returns the content in the file atfilePath.
Example 1:

Input
["FileSystem", "ls", "mkdir", "addContentToFile", "ls", "readContentFromFile"]
[[], ["/"], ["/a/b/c"], ["/a/b/c/d", "hello"], ["/"], ["/a/b/c/d"]]
Output
[null, [], null, null, ["a"], "hello"]
Explanation
FileSystem fileSystem = new FileSystem();
fileSystem.ls("/"); // return []
fileSystem.mkdir("/a/b/c");
fileSystem.addContentToFile("/a/b/c/d", "hello");
fileSystem.ls("/"); // return ["a"]
fileSystem.readContentFromFile("/a/b/c/d"); // return "hello"
Constraints:
1 <= path.length, filePath.length <= 100pathandfilePathare absolute paths which begin with'/'and do not end with'/'except that the path is just"/".- You can assume that all directory names and file names only contain lowercase letters, and the same names will not exist in the same directory.
- You can assume that all operations will be passed valid parameters, and users will not attempt to retrieve file content or list a directory or file that does not exist.
- You can assume that the parent directory for the file in
addContentToFilewill exist. 1 <= content.length <= 50- At most
300calls will be made tols,mkdir,addContentToFile, andreadContentFromFile.
Solution
Approach: Trie of Path Names
A file system is a tree: every directory has children, each with a name, and files are leaves that hold content. That is a trie whose edges are path segments instead of characters. Each node keeps:
children: a map from a name to the child node,isFile: whether this node is a file,content: the file's text, built up by appends.
All four operations start the same way: split the path on / and walk down from the root, one segment at a time. Skip empty segments, so the leading / and the path "/" itself (which splits into two empty strings) both lead to the root. A single walk helper that creates missing nodes as it goes serves every operation:
mkdir(path): just walk the path; the missing directories, including the middle ones, are created on the way.addContentToFile(filePath, content): walk to the node (creating it if it is new), mark it as a file and appendcontent. Appending to an existing file is the same code.readContentFromFile(filePath): walk to the node and return its content.ls(path): walk to the node. If it is a file, return a list with only its own name, the last segment ofpath. Otherwise return its children's names in sorted order.
The case people miss is ls on a file: it must return [name], not the (empty) list of children. Using a sorted map (TreeMap in Java, map in C++) gives the names in order for free; in the other languages we sort them in ls.
Complexity: Each operation walks a path of length L in O(L) time (plus O(c) to append or read content of length c). ls on a directory with k entries also sorts them: O(k log k). The space is the total length of all paths and contents.
class Node:
def __init__(self):
self.children = {} # name -> Node
self.is_file = False
self.content = [] # appended pieces of a file's content
class FileSystem:
def __init__(self):
self.root = Node()
def _walk(self, path: str) -> Node:
"""The node at path, creating missing directories on the way."""
node = self.root
for name in path.split("/")[1:]:
if name: # "/" splits into ["", ""]
node = node.children.setdefault(name, Node())
return node
def ls(self, path: str) -> List[str]:
node = self._walk(path)
if node.is_file:
return [path.split("/")[-1]]
return sorted(node.children)
def mkdir(self, path: str) -> None:
self._walk(path)
def addContentToFile(self, filePath: str, content: str) -> None:
node = self._walk(filePath)
node.is_file = True
node.content.append(content)
def readContentFromFile(self, filePath: str) -> str:
return "".join(self._walk(filePath).content)