Designing a File System

Difficulty: Intermediate Patterns: Composite, Template Method, Iterator Asked at: Uber, Amazon, Google, Microsoft, Flipkart

💡 Design pattern = a named, reusable solution to a problem that keeps recurring in object-oriented code, which is why interviewers expect the vocabulary. The machine coding round primer explains what they are grading.


Functional Requirements

  1. mkdir — create a directory at a given path, creating intermediate directories if needed (like mkdir -p)
  2. ls — list contents of a directory, sorted alphabetically
  3. touch — create a file at a given path
  4. rm — remove a file or empty directory
  5. pwd / resolve — resolve an absolute path to the corresponding node in the tree

Non-Functional Requirements

  1. Extensibility — adding new node types (symlinks, devices) should be minimal code change
    💡 This is the open/closed idea from SOLID: a new node type should arrive as a new class, not as edits scattered through working code.
  2. Thread-safety — concurrent mkdir/ls calls shouldn’t corrupt the tree
    💡 Thread-safety = the code still behaves correctly when several threads run it at the same instant. Two threads creating /home/user together must not both insert a user child.
  3. O(d) path resolution — where d is depth of the path (same as real file systems)
    💡 O(d) = the cost grows with the depth of the path, not with the total number of files. Resolving /a/b/c touches three nodes whether the tree holds ten files or ten million.

Core Entities

Entity Description
FileSystemNode Abstract base — name, parent reference, path computation
Directory A node that can contain children (other nodes)
File A leaf node with optional content
FileSystem The API layer — owns the root directory, exposes mkdir/ls/touch/rm

💡 Abstract base class = a half-finished class you cannot instantiate on its own. It holds the fields and code every node shares (name, parent, getPath()) and leaves one hole, isDirectory(), for each subclass to fill.

💡 Leaf vs composite = in a tree a leaf has no children (File) while a composite holds other nodes (Directory). Both answer the same base-class methods, which is what lets callers treat one file and a whole subtree identically.


Class Diagram

classDiagram
    class FileSystemNode {
        <<abstract>>
        #String name
        #Directory parent
        +getName() String
        +getPath() String
        +isDirectory() boolean*
    }

    class File {
        -String content
        +isDirectory() boolean
        +getContent() String
        +setContent(String)
    }

    class Directory {
        -TreeMap~String FileSystemNode~ children
        +addChild(FileSystemNode)
        +getChild(String) FileSystemNode
        +hasChild(String) boolean
        +removeChild(String)
        +listChildren() List~String~
        +isDirectory() boolean
    }

    class FileSystem {
        -Directory root
        -ReentrantReadWriteLock lock
        +mkdir(String path)
        +ls(String path) List~String~
        +touch(String path)
        +rm(String path)
        +find(String path String pattern) List~String~
        -resolve(String path) FileSystemNode
    }

    FileSystemNode <|-- File
    FileSystemNode <|-- Directory
    Directory o-- FileSystemNode : children
    FileSystem --> Directory : root

💡 In a UML class diagram the hollow-triangle arrow <|-- means “extends this class”, o-- means “contains these objects”, --> means “holds a reference to”, # marks a protected field and a trailing * marks an abstract method.


Design Patterns

Pattern Where Why
Composite FileSystemNode → Directory (composite) / File (leaf) A directory IS-A node that CONTAINS nodes. Uniform treatment of files and directories. This is the textbook use case for Composite.
Template Method getPath() in base class calls parent.getPath() recursively Path computation is the same algorithm for every node type — only isDirectory() varies.
Iterator (extension) find() does DFS over the composite tree Traversal logic is decoupled from node structure.

💡 Composite pattern = give a container and a single item the same interface so client code can treat “one file” and “a directory full of files” the same way, recursively.

💡 Template method pattern = the base class fixes the shape of an algorithm and leaves named holes for subclasses. getPath() is the fixed walk up the tree; isDirectory() is the hole.

💡 Iterator = a pattern that hands callers a way to step through a structure without knowing how it is stored. It is what keeps the find() traversal out of Directory itself.

💡 DFS = depth-first search: follow one branch as deep as it goes before backing up and trying the next. It is the natural way to visit every node under a directory.


Data Structures

Component Structure Why
Children of a directory TreeMap<String, FileSystemNode> O(log n) insert, automatically sorted keys → ls returns alphabetical order for free
Path resolution Split path by /, walk tree O(d) where d = depth, matches real FS behavior
Root reference Single Directory object Entry point for all operations

💡 TreeMap = a map that keeps its keys in sorted order rather than hash order, which costs O(log n) per operation instead of O(1). We pay that log n so ls never has to sort anything.


How It All Fits Together

mkdir(“/home/user/documents”):

  1. Split path into ["home", "user", "documents"]
  2. Start at root. Check if home exists — if not, create Directory(“home”, root), add as child
  3. Move into home. Check if user exists — if not, create and add
  4. Move into user. Check if documents exists — if not, create and add
  5. Each step: O(log n) lookup in TreeMap. Total: O(d × log n) where d=3, n=children per level

ls(“/home/user”):

  1. Resolve path → get the user Directory node
  2. Call listChildren() → returns TreeMap keys (already sorted)
  3. Return ["documents"]

Key design decision: mkdir is idempotent — calling it on an existing directory is a no-op. But calling it where a file exists at that path is an error.


Complete Code

FileSystemNode.java

The abstract base class. Every node knows its name and parent. getPath() walks up the tree recursively — no need to store full paths (which would break on renames). isDirectory() is the single abstract method that subclasses implement.