Taro Logo

Design In-Memory File System

#2 Most AskedHard
0 views
Topics:
TreesStrings

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. You can assume that all file or directory paths start with '/'.
  2. You can assume that all file names and directory names only contain lower-case letters, and digits.
  3. You can assume that each path is a valid absolute path which does not have invalid dots like '/..'.
  4. You can assume that all operations will be passed valid parameters.
  5. You can assume that the length of the path is between 1 and 300.
  6. The number of calls to each function is at most 100.

Solution


Clarifying Questions

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:

  1. Are the file paths always given as absolute paths starting with '/', or can we expect relative paths as well?
  2. When listing the contents of a directory or a file via `ls`, if the path points to a file rather than a directory, should it return a list containing just the file name?
  3. Can files and directories share the same name within the same parent directory, or are names guaranteed to be unique across both types?
  4. When appending content to a file using `addContentToFile`, if the file does not yet exist, should it be automatically created?
  5. Are the directory and file names guaranteed to be valid strings (e.g., alphanumeric without special characters), or can they contain spaces and slashes?

Brute Force Solution

Approach

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:

  1. Whenever someone asks to read a file or look inside a folder, start at the very beginning of your entire collection of stored items.
  2. Inspect every single item one by one, checking if its full path matches the exact name of the file or folder you are looking for.
  3. If you are asked to create a new file or add text to an existing one, scan through all your saved items to see if it already exists.
  4. If it is already there, go through the text and add the new information directly to it.
  5. If it is not there, simply add this new item to the very end of your giant pile of stored things.
  6. Whenever someone asks for a list of everything inside a folder, look through every single item in your entire collection and pick out the ones that belong inside that specific folder.
  7. Repeat this exhaustive search and scan process completely from scratch for every single command you receive, no matter how many items you have stored.

Code Implementation

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 ""

Big(O) Analysis

Time Complexity
O(m * n) – For each of the m total commands received by the file system, the brute force approach must perform an exhaustive scan of all n stored items in the collection. Depending on the operation, it either inspects every single item to match a path or filters through the entire pile to list folder contents. This requires n operations for each of the m commands, leading to approximately m * n total operations, which simplifies to O(m * n).
Space Complexity
O(N) – To execute the operations described, the brute-force approach requires storing all items in a single collection, where N represents the total number of files and folders created. Auxiliary memory is consumed by this giant list containing every individual item and its corresponding text content. As new files or folders are added, this collection grows linearly, directly scaling the extra memory required. Therefore, the total auxiliary space complexity simplifies to Big O of N based on the total number of stored entities.

Optimal Solution

Approach

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:

  1. Imagine the entire file system as a giant family tree, starting with a grand entrance at the very top representing the root directory.
  2. Give every folder the ability to hold a list of its subfolders and a collection of text documents, along with the actual text content if it happens to be a file.
  3. When someone asks for a list of contents at a specific path, break the path down into individual names and follow the folder branches one by one until you reach the correct destination.
  4. If the destination is a file, simply hand back its name, but if the destination is a folder, gather and alphabetize all the names of the items inside it to return a neat list.
  5. When someone wants to create a new folder, follow the path piece by piece, and whenever a folder along the way does not exist yet, build it on the spot.
  6. When someone wants to write or add text to a file, navigate directly to the file's location using its path, creating any missing parent folders along the way if necessary, and then update or append the text inside it.
  7. When someone wants to read a file, follow the path directly to the document and instantly retrieve the text stored inside without having to look anywhere else.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(L + K log K) – To navigate or modify any path, we first split the string into L path components and traverse that many tree nodes, which takes O(L) time where L is the length of the path. When listing the contents of a directory, we also must sort K filenames contained within that folder, taking O(K log K) time. The total operations scale with the depth of the path and the number of items inside the target directory, making the overall complexity O(L + K log K).
Space Complexity
O(N) – To analyze the auxiliary space complexity, let N be the total number of unique characters across all file and folder names stored in the system, along with the total content appended to all files. The trie-like tree structure stores hash maps at each directory node to map sub-folder and file names to their respective child nodes, consuming memory proportional to the length and number of paths created. During operations like listing directory contents, temporary lists are dynamically allocated to collect, sort, and return the names of all items residing inside a specific folder. Similarly, writing or reading file content utilizes string storage directly within the leaf nodes, meaning the extra memory scales linearly with the total volume of data inserted into the file system.

Edge Cases

Path starts with a root slash but contains multiple consecutive slashes like a//b
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
Traverse the Trie or hash map structure level by level until reaching the target file node.
Directory listing output must be sorted lexicographically
How to Handle:
Collect all child names from the node and apply a standard string sorting algorithm before returning.
Multiple consecutive append operations on the same file
How to Handle:
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
How to Handle:
Traverse the existing path without overwriting or resetting the node to preserve its current contents.
0/2 completed