Design In-Memory File System - Problem
๐๏ธ Design In-Memory File System
Imagine you're building a cloud storage system that needs to simulate a complete file system entirely in memory. You need to create a data structure that can handle all the basic operations you'd expect from a real file system: listing directories, creating folders, writing files, and reading their contents.
Your FileSystem class should support these operations:
- List Directory/File (
ls): Given a path, return all files and folders in lexicographic order. If it's a file, return just that filename. - Create Directory (
mkdir): Create a new directory (and any missing parent directories) at the given path. - Write/Append to File (
addContentToFile): Create a new file with content, or append to existing file content. - Read File (
readContentFromFile): Return the complete content of a file.
Think of it like implementing your own version of a simplified Unix file system commands!
Input & Output
Basic Operations
$
Input:
fs = FileSystem()
fs.ls("/") # []
fs.mkdir("/a/b/c")
fs.addContentToFile("/a/b/c/d", "hello")
fs.ls("/") # ["a"]
fs.readContentFromFile("/a/b/c/d") # "hello"
โบ
Output:
[]
["a"]
"hello"
๐ก Note:
Create directory structure, add file with content, then list and read operations work correctly
File vs Directory Listing
$
Input:
fs = FileSystem()
fs.addContentToFile("/goowmfn", "c")
fs.ls("/goowmfn") # ["goowmfn"]
fs.ls("/") # ["goowmfn"]
โบ
Output:
["goowmfn"]
["goowmfn"]
๐ก Note:
When ls() is called on a file path, it returns just the filename. When called on directory containing that file, it lists the file.
Content Appending
$
Input:
fs = FileSystem()
fs.addContentToFile("/a", "hello")
fs.addContentToFile("/a", " world")
fs.readContentFromFile("/a") # "hello world"
โบ
Output:
"hello world"
๐ก Note:
Multiple calls to addContentToFile append content to existing files rather than overwriting
Constraints
- 1 โค path.length, filePath.length โค 100
- 1 โค content.length โค 50
- All paths are absolute paths starting with '/' and do not end with '/' except for root
- At most 300 calls will be made to the methods
- File and directory names consist of only lowercase English letters and digits
Visualization
Tap to expand
Understanding the Visualization
1
Root Foundation
Start with root node (/) as the foundation of our file system tree
2
Branch Navigation
Each path component leads us down a specific branch in the tree
3
Efficient Access
Operations only traverse the path depth, not the entire file system
Key Takeaway
๐ฏ Key Insight: By representing the file system as a tree where each node is a directory containing files and subdirectories, we achieve O(path_depth) complexity for all operations - much faster than linear searching through all paths.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code