This problem requires designing an in-memory file system. The solution uses a Trie data structure to efficiently store and retrieve file and directory information. A Trie is a tree-like data structure where each node represents a part of a path (e.g., directory or file name). This allows for quick lookups and insertions based on paths.
Data Structure (Trie):
Each Trie node contains:
name
: The name of the file (only for file nodes).isFile
: A boolean indicating whether the node represents a file or a directory.content
: A string builder (or equivalent) to store the file content (only for file nodes).children
: A map (dictionary) to store child nodes (subdirectories or files within this directory).Methods:
FileSystem()
: Initializes the file system with an empty root Trie node.
ls(path)
:
path
in the Trie. If the path doesn't exist, it returns an empty list.children
map of the directory node).mkdir(path)
:
path
into the Trie as a directory (isFile = False
). If intermediate directories along the path don't exist, they are also created.addContentToFile(filePath, content)
:
filePath
into the Trie as a file (isFile = True
). If the file already exists, the new content
is appended to its existing content.readContentFromFile(filePath)
:
filePath
in the Trie. It returns the content of the file if found.Time Complexity Analysis:
ls(path)
: O(P log P), where P is the length of the path. The search operation in the Trie takes O(P) time. Sorting the directory contents takes O(P log P) time in the worst case (where P is the number of files/directories in the directory).
mkdir(path)
: O(P), where P is the length of the path. The Trie insertion operation takes O(P) time in the worst case.
addContentToFile(filePath, content)
: O(F), where F is the length of the filePath. Trie insertion and appending content takes O(F) time.
readContentFromFile(filePath)
: O(F), where F is the length of the filePath. Trie search operation takes O(F) time.
Space Complexity Analysis:
The space complexity is O(N), where N is the total number of files and directories in the file system. This is because the Trie structure stores all the file and directory information.
Example Code (Python):
The Python code provided above implements the FileSystem
class using a Trie data structure as described. The Java and Go code offer equivalent implementations in their respective languages. All implementations follow the same Trie-based approach to handle file system operations efficiently.