Simulate a File System (Trie-based; validate directory hierarchy before adding a file)
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2020-11-04
Problem Statement
Designing a simplified in-memory file system that allows creating directories and files while ensuring that the directory hierarchy is valid before insertion. The implementation should be based on a Trie-like structure, where each node represents either a directory or a file.
Functional Requirements
1.Create Directory
•Support creating a directory at a given path.
•Example: mkdir("/usr/local/bin")
•Should create intermediate directories if they don’t exist.
2.Add File
•Support adding a file at a given path.
•Example: addFile("/usr/local/bin/script.sh")
•Should only succeed if parent directories exist.
•If parent doesn’t exist → throw error.
3.Validate Directory Hierarchy
•Before adding a file, check if all parent directories exist.
•Example:
•✅ /usr/local/bin/ exists → allow adding file.
•❌ /random/path/file.txt → reject (missing parent dirs).
4.Search / Exists
•Query if a given path (directory or file) exists.
5.List Contents
•Ability to list files/directories under a given path.
•Example: ls("/usr/local") → ["bin"]
6.Edge Cases
•Empty root / must always exist.
•Cannot overwrite a directory with a file or vice versa.
•No duplicate file/directory names under the same parent.
Non-Functional Requirements
•Scalability: Handle deeply nested directory structures.
•Efficiency: File lookups and insertions should be near O(L), where L = length of path.
•Consistency: Strict separation between files and directories.
•Clean Design: Classes should be extensible for future operations (e.g., delete, move).
Design Hints for Interview
•Use a Trie-like structure:
•Each node stores:
•name (string)
•children (map of name → node)
•isFile (boolean)
•Classes to consider:
•FileSystem → main entry class with operations (mkdir, addFile, ls, exists).
•Node → represents either directory or file.
Example Scenario
1
2mkdir("/usr")
3mkdir("/usr/local")
4mkdir("/usr/local/bin")
5addFile("/usr/local/bin/script.sh")
6
7ls("/usr/local") → ["bin"]
8exists("/usr/local/bin/script.sh") → true
9addFile("/random/file.txt") → Error (parent dirs missing)✅ This problem is strong for LLD interviews because it tests class design, tree/Trie usage, hierarchy validation, and edge case handling.