Design an in-memory Unix-like file system. The interview is reported as a two-part coding question and is similar in spirit to LeetCode 588: Design In-Memory FileSystem.
Implement an in-memory file system similar to a Unix-like file system. The file system should support the following operations:
Create a file:
createFile("/file1", "content")True (indicating the file was successfully created)Delete a file:
deleteFile("/file1")True (indicating the file was successfully deleted)Read a file:
readFile("/file1")"content" (the content of the file)List directory:
listDirectory("/")["file1"] (list of files in the root directory)Read directory:
readDirectory("/file1")"content" (the content of the directory, if it exists)`python class TrieNode: def init(self): self.children = {} self.is_file = False self.content = ""
class FileSystem: def init(self): self.root = TrieNode()
def create_file(self, path, content):
node = self.root
for part in path.split("/"):
if part not in node.children:
node.children[part] = TrieNode()
node = node.children[part]
node.is_file = True
node.content = content
return True
def delete_file(self, path):
node = self.root
for part in path.split("/"):
if part not in node.children:
return False
node = node.children[part]
if not node.is_file:
return False
node.is_file = False
node.content = ""
return True
def read_file(self, path):
node = self.root
for part in path.split("/"):
if part not in node.children:
return None
node = node.children[part]
if not node.is_file:
return None
return node.content
def list_directory(self, path):
node = self.root
for part in path.split("/"):
if part not in node.children:
return []
node = node.children[part]
return list(node.children.keys())
def read_directory(self, path):
node = self.root
for part in path.split("/"):
if part not in node.children:
return None
node = node.children[part]
if node.is_file:
return node.content
return " ".join(node.children.keys())
fs = FileSystem() fs.create_file("/file1", "content") print(fs.read_file("/file1")) # Output: "content" fs.delete_file("/file1") print(fs.read_file("/file1")) # Output: None `
This solution uses a trie data structure to efficiently store and retrieve file paths, and a hash map to store file contents for quick access. The create_file, delete_file, read_file, list_directory, and read_directory methods implement the required operations of the in-memory file system.