Design a File System with Hierarchical Structure

Difficulty: EASYCategory: LLDFrequency: 1Asked On 2025-06-13

Problem Statement

Design and implement a simplified in-memory file system that models a hierarchical directory structure. The system should support files and folders using composition, and operations like creation, deletion, size calculation, and path navigation.


🎯 Functional Requirements

Implement the following operations:

1.createFile(String path, String fileName, int size)
•Creates a file under the given path with specified size in bytes.
2.createFolder(String path, String folderName)
•Creates a folder under the given path.
3.delete(String path)
•Deletes the file or folder at the given path (recursively if folder).
4.getSize(String path)
•Returns the size (in bytes):
•For a file: its own size
•For a folder: sum of all nested file sizes
5.listContents(String path)
•Lists all direct contents (files and folders) under the given folder path.


🧱 Design Requirements

•Use composition:
•A Folder contains FileSystemItem objects (which can be files or folders).
•Use hierarchical modeling:
•Directories and subdirectories form a tree structure.


📐 Suggested Class Design

Interface / Abstract Class: FileSystemItem

•String name
•String path
•int getSize()
•boolean isFile()

Class: File (inherits FileSystemItem)

•int size

Class: Folder (inherits FileSystemItem)

•Map<String, FileSystemItem> children

Class: FileSystem

•Root folder
•Methods for create, delete, list, and size

⚖️ Constraints

•Paths are UNIX-like: /, /home, /home/user/docs
•No duplicate names allowed in the same folder
•Folder size is dynamic (recomputed recursively)

🧪 Sample Test Case

1plaintext 2CopyEdit 3createFolder("/", "docs") 4createFile("/docs", "file1.txt", 100) 5createFolder("/docs", "subfolder") 6createFile("/docs/subfolder", "file2.txt", 200) 7 8getSize("/docs") → 300 9listContents("/docs") → [file1.txt, subfolder] 10delete("/docs/subfolder") 11getSize("/docs") → 100


🔧 Brute-force vs Optimized

•Brute-force: Every getSize() call walks the tree recursively.
•Optimized: Cache sizes and update them incrementally on file/folder creation or deletion.


✅ Evaluation Criteria

•Use of composition and hierarchy (files inside folders inside folders).
•Correct recursive logic for size and deletion.
•Extensibility: Easy to add move/rename/search features later.
•Clean code and working test cases.
•Optimization discussion (lazy caching, etc.).


Solution

Comments