PythonStudio
Interview Problems

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

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.

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'))

Starter code

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 compiler