Skip to content
BytePatterns

In-Memory File System

HardLow-Level Design#class-design#path-walk#invariants~35m

Problem

Design an in-memory file system with absolute, slash-separated paths. mkdir(path) creates a directory and any missing parents. append(path, text) creates a file if needed, including missing parent directories, and adds text to its end. read(path) returns a file's whole content, ls(path) returns the sorted names inside a directory, or a one-item list with the file's own name for a file, and size(path) returns the total characters stored at or below a path. The structure must stay a valid tree: nothing may be created inside a file, and a directory may never be read or appended to, so those calls raise NotADirectoryError or IsADirectoryError and change nothing.

Examples

Input:  mkdir("/logs/app"), append("/logs/app/today.txt", "boot ok\n"),
        append("/logs/app/today.txt", "user in\n"), append("/notes/todo.md", "ship it")
        ls("/"), ls("/logs/app"), ls("/notes/todo.md")
Output: ['logs', 'notes'] ['today.txt'] ['todo.md']
Input:  then read("/logs/app/today.txt"), size("/")
Output: 'boot ok\nuser in\n' 23
Why:    8 + 8 characters in today.txt and 7 in todo.md
Input:  then mkdir("/notes/todo.md/drafts"), append("/logs", "x")
Output: NotADirectoryError IsADirectoryError
Why:    edge case, the tree refuses a folder inside a file and text written to a folder

Hints

0 / 3

Stuck on the idea rather than the code? Designing a File System covers it.