Design an in-memory file system to simulate the following functions:
ls: Given a path in string format. If it is a file path, return a list that only contains this file's name. If it is a directory path, return the list of file and directory names in lexicographical order.mkdir: Given a directory path that does not exist, you should make a new directory. If the middle directories in the path do not exist either, you should create them as well. This function has void return type.addContentToFile: Given a file path and content in string format. If the file doesn't exist, you should create that file. Then append the given content to that file. This function has void return type.readContentFromFile: Given a file path, return the content in string format.Example:
Input:
["FileSystem","ls","mkdir","addContentToFile","ls","readContentFromFile"]
[[],["/"],["/a/b/c"],["/a/b/c/d","hello"],["/"],["/a/b/c/d"]]
Output:
[null,[],null,null,["a"],"hello"]
Explanation:
FileSystem fileSystem = new FileSystem();
fileSystem.ls("/"); // return []
fileSystem.mkdir("/a/b/c");
fileSystem.addContentToFile("/a/b/c/d", "hello");
fileSystem.ls("/"); // return ["a"]
fileSystem.readContentFromFile("/a/b/c/d"); // return "hello"
Note:
'/'.'/..'.1 and 300.100.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine organizing a giant filing cabinet where every single document and folder is stored in one enormous, unorganized pile. The brute force approach simply searches through this entire pile from scratch every single time someone asks to look at a file, list a folder, or write down some text.
Here's how the algorithm would work step-by-step:
class FileSystem:
def __init__(self):
self.storage_pile = []
def ls(self, file_path):
# We must scan the entire pile to find matching paths or parent directory contents
directory_contents = []
if any(item["path"] == file_path and item["type"] == "file" for item in self.storage_pile):
return [file_path.split("/")[-1]]
target_prefix = file_path if file_path == "/" else file_path + "/"
for stored_item in self.storage_pile:
stored_path = stored_item["path"]
if stored_path.startswith(target_prefix):
relative_path = stored_path[len(target_prefix):]
first_segment = relative_path.split("/")[0]
if first_segment and first_segment not in directory_contents:
directory_contents.append(first_segment)
return sorted(directory_contents)
def mkdir(self, file_path):
# We iterate through the whole pile to ensure we do not duplicate existing directories
path_exists = False
for stored_item in self.storage_pile:
if stored_item["path"] == file_path:
path_exists = True
break
if not path_exists:
self.storage_pile.append({"path": file_path, "type": "directory", "content": ""})
def add_content_to_file(self, file_path, file_content):
# We scan every item to check if the file already exists before appending or creating
file_found = False
for stored_item in self.storage_pile:
if stored_item["path"] == file_path:
stored_item["content"] += file_content
file_found = True
break
if not file_found:
self.storage_pile.append({"path": file_path, "type": "file", "content": file_content})
def read_content_from_file(self, file_path):
# We search through the entire collection from scratch to locate the requested file text
for stored_item in self.storage_pile:
if stored_item["path"] == file_path:
return stored_item["content"]
return ""To build an efficient in-memory file system, we can borrow the way a real library organizes its books by using a tree structure where folders act as branching hallways and files act as the final books on the shelves. This allows us to instantly navigate to any path by following the directory signs step by step rather than searching blindly through everything.
Here's how the algorithm would work step-by-step:
class FileSystemNode:
def __init__(self):
self.subdirectories = {}
self.file_contents = ""
self.is_file_flag = False
class FileSystem:
def __init__(self):
self.root_directory = FileSystemNode()
def ls(self, directory_path: str) -> list:
current_node = self.root_directory
if directory_path != "/":
path_segments = directory_path.split("/")[1:]
for segment in path_segments:
current_node = current_node.subdirectories[segment]
# If destination is a file, return just its name to satisfy API specifications.
if current_node.is_file_flag:
return [directory_path.split("/")[-1]]
return sorted(list(current_node.subdirectories.keys()))
def mkdir(self, directory_path: str) -> None:
current_node = self.root_directory
path_segments = directory_path.split("/")[1:]
# Build missing folders on the spot to ensure valid navigation paths.
for segment in path_segments:
if segment not in current_node.subdirectories:
current_node.subdirectories[segment] = FileSystemNode()
current_node = current_node.subdirectories[segment]
def add_content_to_file(self, file_path: str, content: String) -> None:
current_node = self.root_directory
path_segments = file_path.split("/")[1:]
for segment in path_segments[:-1]:
if segment not in current_node.subdirectories:
current_node.subdirectories[segment] = FileSystemNode()
current_node = current_node.subdirectories[segment]
file_name = path_segments[-1]
if file_name not in current_node.subdirectories:
current_node.subdirectories[file_name] = FileSystemNode()
target_file_node = current_node.subdirectories[file_name]
target_file_node.is_file_flag = True
# Append incoming text content directly into the file node storage.
target_file_node.file_contents += content
def read_content_from_file(self, file_path: str) -> str:
current_node = self.root_directory
path_segments = file_path.split("/")[1:]
for segment in path_segments:
current_node = current_node.subdirectories[segment]
return current_node.file_contents| Case | How to Handle |
|---|---|
| Path starts with a root slash but contains multiple consecutive slashes like a//b | Split the path string by slashes and filter out empty tokens to prevent empty directory node creation. |
| Creating a directory whose intermediate parent directories do not yet exist | Iterate through each path component and automatically instantiate missing directory nodes along the traversal. |
| Appending content to a file that does not yet exist in the file system | Automatically create the file node with empty content before appending the new data string. |
| Listing the contents of a path that points directly to a file instead of a directory | Return a list containing only the single file name as per standard file system behavior. |
| Reading content from a file path that has multiple nested directories | Traverse the Trie or hash map structure level by level until reaching the target file node. |
| Directory listing output must be sorted lexicographically | Collect all child names from the node and apply a standard string sorting algorithm before returning. |
| Multiple consecutive append operations on the same file | Concatenate the new content string to the existing string stored within the file node efficiently. |
| Creating a directory path that already exists as a directory | Traverse the existing path without overwriting or resetting the node to preserve its current contents. |