588. Design In-Memory File System
Problem
Design an in-memory FileSystem: ls(path) returns [name] for a file path or the sorted names inside a directory; mkdir(path) creates the directory and any missing parents; addContentToFile(filePath, content) creates the file or appends to it; readContentFromFile(filePath) returns the file's content.
Example: ls("/") → []; mkdir("/a/b/c"); addContentToFile("/a/b/c/d","hello") → ls("/") = ["a"], readContentFromFile("/a/b/c/d") = "hello"
Problem (Premium): implement ls(path) (a file path → [file name]; a directory → its children's names sorted), mkdir(path) (creating missing parents), addContentToFile(filePath, content) (create or append) and readContentFromFile(filePath). Paths are absolute, like /a/b/c.
A trie keyed by path components: each node has a sorted map of children and, for files, a content buffer. Walking a path is O(depth); ls of a directory sorts its children (or keep a sorted map).
Complexity: O(path length) per walk, plus O(k log k) for ls of a directory with k entries.
class FileSystem:
def __init__(self):
self.root = {"kids": {}, "file": None} # file: None for a directory, else its content
def _walk(self, path):
node = self.root
for part in filter(None, path.split("/")):
node = node["kids"].setdefault(part, {"kids": {}, "file": None})
return node
def ls(self, path: str) -> List[str]:
node = self._walk(path)
return [path.rsplit("/", 1)[1]] if node["file"] is not None else sorted(node["kids"])
def mkdir(self, path: str) -> None:
self._walk(path)
def addContentToFile(self, filePath: str, content: str) -> None:
node = self._walk(filePath)
node["file"] = (node["file"] or "") + content
def readContentFromFile(self, filePath: str) -> str:
return self._walk(filePath)["file"]
fs = FileSystem()
assert fs.ls("/") == []
fs.mkdir("/a/b/c")
fs.addContentToFile("/a/b/c/d", "hello")
assert fs.ls("/") == ["a"]
assert fs.readContentFromFile("/a/b/c/d") == "hello"
fs.addContentToFile("/a/b/c/d", " world")
assert fs.readContentFromFile("/a/b/c/d") == "hello world"
assert fs.ls("/a/b/c/d") == ["d"]
fs.mkdir("/a/b/e")
fs.addContentToFile("/a/b/aa", "x")
assert fs.ls("/a/b") == ["aa", "c", "e"]
class FileSystem {
private static class Node { TreeMap<String, Node> kids = new TreeMap<>(); StringBuilder file; }
private final Node root = new Node();
private Node walk(String path) {
Node node = root;
for (String part : path.split("/")) if (!part.isEmpty()) node = node.kids.computeIfAbsent(part, k -> new Node());
return node;
}
public List<String> ls(String path) {
Node node = walk(path);
if (node.file != null) return List.of(path.substring(path.lastIndexOf('/') + 1));
return new ArrayList<>(node.kids.keySet());
}
public void mkdir(String path) { walk(path); }
public void addContentToFile(String filePath, String content) {
Node node = walk(filePath);
if (node.file == null) node.file = new StringBuilder();
node.file.append(content);
}
public String readContentFromFile(String filePath) { return walk(filePath).file.toString(); }
}
type fsNode struct {
kids map[string]*fsNode
isFile bool
content string
}
type FileSystem struct {
root *fsNode
}
func Constructor() FileSystem {
return FileSystem{root: &fsNode{kids: map[string]*fsNode{}}}
}
func (this *FileSystem) walk(path string) *fsNode { // creates missing directories on the way
node := this.root
for _, part := range strings.Split(path, "/") {
if part == "" {
continue
}
next, ok := node.kids[part]
if !ok {
next = &fsNode{kids: map[string]*fsNode{}}
node.kids[part] = next
}
node = next
}
return node
}
func (this *FileSystem) Ls(path string) []string {
node := this.walk(path)
if node.isFile {
return []string{path[strings.LastIndex(path, "/")+1:]}
}
names := []string{}
for name := range node.kids {
names = append(names, name)
}
sort.Strings(names)
return names
}
func (this *FileSystem) Mkdir(path string) {
this.walk(path)
}
func (this *FileSystem) AddContentToFile(filePath string, content string) {
node := this.walk(filePath)
node.isFile = true
node.content += content
}
func (this *FileSystem) ReadContentFromFile(filePath string) string {
return this.walk(filePath).content
}