Problem statement

https://binarysearch.com/problems/File-System/

Solution

We can use trie in this problem.

Complexity

It is O(n) for time for get and create, where n is the length of input. Space potentially is O(sum(lengths)).

Code

class TrieNode:
    def __init__(self):
        self.children = {}
        self.value = -1

class FileSystem:
    def __init__(self):
        self.tree = TrieNode()
        self.tree.children[""] = TrieNode()

    def get(self, path):
        node = self.tree
        for path in path.split("/"):
            if path not in node.children: return -1
            node = node.children[path]
        return node.value
        
    def create(self, path, content):
        node = self.tree
        folders = path.split("/")
        for idx, path in enumerate(folders):
            if path not in node.children:
                if idx < len(folders) - 1: return False
                node.children[path] = TrieNode()
            node = node.children[path]
        if node.value != -1: return False
        node.value = content
        return True