Design In-Memory File System

Hard · Design · Design · Trie · Hash Table · String · Sorting

Problem

Build a file system that lives entirely in memory. Paths are absolute, like /a/b/c, and / is the root.

Every call is valid: you are never asked to list or read a path that does not exist, mkdir never names an existing directory, and a new file's parent directory already exists.

Your tests replay a call sequence: the first entry names the class, each later entry is a method with its arguments, and calls returning nothing report None.

Examples

Input: ls("/"), mkdir("/a/b/c"), addContentToFile("/a/b/c/d", "hello"), ls("/"), readContentFromFile("/a/b/c/d")
Output: [], then ["a"], then "hello"

The root starts empty. mkdir builds a, b and c in one call, and d becomes a file inside c. Listing the root shows only a, the one entry directly inside it.

Input: mkdir("/docs"), addContentToFile("/docs/todo", "buy"), addContentToFile("/docs/todo", " milk"), ls("/docs/todo"), ls("/docs"), readContentFromFile("/docs/todo")
Output: ["todo"], then ["todo"], then "buy milk"

The second add appends to the existing file. Listing a file path returns just its own name.

Constraints

Approaches

Follow-up

What if one directory holds a million entries and is listed constantly, or a file grows by millions of small appends? Sorting on every ls and rebuilding a string on every append both become the bottleneck; keep children in a sorted structure and content as a list of chunks.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…