AAI Agentic Handbook
Problem 76 · Object & System Design

In-Memory File System

HardClassic DSA & systems
01Problem

Implement ls(path), mkdir(path), add_content_to_file(path, content), and read_content_from_file(path). ls on a file returns [filename]; on a directory returns sorted children. mkdir and add_content create missing parents.

02Key insight

Model it as a trie keyed by path segments, where each node is either a directory (children map) or a file (content buffer). All operations become a walk over split path components.

03Solution

Try it first.

TimeO(depth) per op (+ k log k for ls sort)
SpaceO(nodes + content)
tests.py · 4 passing
tests.pypython18 lines
fs = FileSystem()
assert fs.ls("/") == []
fs.mkdir("/a/b/c")
fs.add_content_to_file("/a/b/c/d", "hello")
fs.add_content_to_file("/a/b/c/d", " world")
assert fs.ls("/") == ["a"] and fs.ls("/a/b/c") == ["d"] and fs.ls("/a/b/c/d") == ["d"]
assert fs.read_content_from_file("/a/b/c/d") == "hello world"
try:
    fs.ls("/missing"); assert False
except FileNotFoundError:
    pass
fs.mkdir("/empty")
for bad in ("/empty", "/"):
    try:
        fs.add_content_to_file(bad, "x"); assert False
    except IsADirectoryError:
        pass
assert fs.ls("/empty") == [] and fs.ls("/") == ["a", "empty"]
04Staff-level follow-up

Concurrent writers? Per-inode locks taken in path order (hand-over-hand) to avoid deadlock; real systems add a separate inode table so rename/hard links are O(1) pointer moves.