Design In-Memory File System - Problem
Design a data structure that simulates an in-memory file system.
Implement the FileSystem class:
FileSystem()- Initializes the object of the systemList<String> ls(String path)- If path is a file path, returns a list that only contains this file's name. If path is a directory path, returns the list of file and directory names in this directory. The answer should be in lexicographic ordervoid mkdir(String path)- Makes a new directory according to the given path. The given directory path does not exist. If the middle directories in the path do not exist, you should create them as wellvoid addContentToFile(String filePath, String content)- If filePath does not exist, creates that file containing given content. If filePath already exists, appends the given content to original contentString readContentFromFile(String filePath)- Returns the content in the file at filePath
Input & Output
Example 1 — Basic File System Operations
$
Input:
operations = ["FileSystem", "ls", "mkdir", "addContentToFile", "ls", "readContentFromFile"]
parameters = [[], ["/"], ["/a/b/c"], ["/a/b/c/d", "hello"], ["/a/b/c"], ["/a/b/c/d"]]
›
Output:
[null, [], null, null, ["d"], "hello"]
💡 Note:
Initialize file system, list root (empty), create directory /a/b/c, add file /a/b/c/d with content "hello", list /a/b/c contents (shows file "d"), read file content (returns "hello")
Example 2 — File Content Append
$
Input:
operations = ["FileSystem", "addContentToFile", "readContentFromFile", "addContentToFile", "readContentFromFile"]
parameters = [[], ["/a", "hello"], ["/a"], ["/a", " world"], ["/a"]]
›
Output:
[null, null, "hello", null, "hello world"]
💡 Note:
Create file /a with "hello", read it (returns "hello"), append " world" to /a, read again (returns "hello world")
Example 3 — Directory Listing
$
Input:
operations = ["FileSystem", "mkdir", "mkdir", "addContentToFile", "ls"]
parameters = [[], ["/a"], ["/b"], ["/c.txt", "content"], ["/"]]
›
Output:
[null, null, null, null, ["a", "b", "c.txt"]]
💡 Note:
Create directories /a and /b, create file /c.txt, then list root directory contents in lexicographic order
Constraints
- 1 ≤ operations.length ≤ 300
- 1 ≤ path.length, filePath.length ≤ 100
- 1 ≤ content.length ≤ 50
- All paths are absolute paths starting with '/'
- All inputs consist of lowercase English letters, digits, '/', and '.'
- You can assume that all operations are valid
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code