SDE & MLE Prep

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"]