File System

medium · tree, paths

Brief-reported interview attribution (unverified): LeetCode 588 is the design-round version of this question

How to approach an LLD round

Requirements

  • Functional: create directories (parents as needed), append content to a file (missing parents → False), list a path (sorted; a file lists itself), read a file (missing → None).
  • Non-functional: directories and files share one interface (a directory can hold either); path resolution must not create anything it should not.
  • Out of scope: permissions, links, deletion.

Statement

Implement a simple in-memory file system. Directories contain sub-directories and files. mkdir creates nested directories as needed. add_content(path, content) creates the file if it does not exist and appends to it if it does. ls(path) lists a directory's children (directories and files, sorted together) or, for a file path, returns just that file's name. read_content(path) returns a file's content, or None if the path is not a file.

class FileSystem:
    def __init__(self):
    def mkdir(self, path):
        # creates all missing directories along the path ("/" already exists)
    def add_content(self, path, content):
        # -> True if the file was created/appended, False if a parent directory is missing
    def ls(self, path):
        # -> sorted list of names; [] for a path that does not exist
    def read_content(self, path):
        # -> content (str), or None if the path is not a file

Rules. Paths are absolute (/a/b/c). ls("/") lists the root. add_content does not create missing parent directories — it returns False instead. read_content on a directory returns None.

Tests use explicit inputs and injected clocks/callbacks. No network, real threads or application-server execution is involved.

Class design (SOLID)

Node (a name) with Directory (children) and File (content) — the Composite pattern (LSP: a directory can hold any node). FileSystem resolves paths by walking directories. Pattern: Composite.

Public demo

# Public demo: run after implementing the class API above.
f = FileSystem()
f.mkdir('/a/b')
f.mkdir('/a/c')
f.add_content('/a/b/f.txt', 'hello')
print(f.read_content('/a/b/f.txt'))

Reference solution and hidden tests

Locked. Open the interactive editor and attempt the problem; the reference, hidden test descriptions, pattern explanation and complexity are available only after an explicit reveal.

Concurrency

A file system is shared: two writers appending to the same file must not interleave, and a mkdir racing an add_content must not lose the file. Guard each directory with a lock, taken top-down in path order. The reference is single-threaded; the locks are described here.

Trade-offs & extensions

Paths are resolved by walking the tree (O(depth)) — fine for a small tree. Extending: a File with metadata (size, modified time) and a Permission check per node.

Starter code

class Node:

    def __init__(self, name):
        """Initialize the state described in the problem."""
        pass

class File(Node):

    def __init__(self, name):
        """Initialize the state described in the problem."""
        pass

    def append(self, content):
        """Implement the return value and rules in the API contract."""
        pass

class Directory(Node):

    def __init__(self, name):
        """Initialize the state described in the problem."""
        pass

    def child_dir(self, name):
        """Implement the return value and rules in the API contract."""
        pass

    def child_file(self, name):
        """Implement the return value and rules in the API contract."""
        pass

    def add_dir(self, name):
        """Implement the return value and rules in the API contract."""
        pass

    def add_file(self, name):
        """Implement the return value and rules in the API contract."""
        pass

    def list_children(self):
        """Implement the return value and rules in the API contract."""
        pass

class FileSystem:

    def __init__(self):
        """Initialize the state described in the problem."""
        pass

    def mkdir(self, path):
        """creates all missing directories along the path ("/" already exists)"""
        pass

    def add_content(self, path, content):
        """-> True if the file was created/appended, False if a parent directory is missing"""
        pass

    def ls(self, path):
        """-> sorted list of names; [] for a path that does not exist"""
        pass

    def read_content(self, path):
        """-> content (str), or None if the path is not a file"""
        pass
Loading editor…

Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.

Return to the Python interpreter

3 comments

Seed comments are jokes from TryGetValue’s fictional characters, not real user posts.

Your posts stay in this browser, for this problem only. They are not shared with other visitors.

  1. TryGetValueCharacter joke · No posting date

    I solved this in O(1). Then I remembered I actually have to write the code. O(n) regrets.

  2. The GraderCharacter joke · No posting date

    Your solution is correct. Your variable names are a crime scene.

  3. TryGetValueCharacter joke · No posting date

    I found the bug. It was me. I was the bug.