Approach
Sorting and greedy selection
For Design in Memory File System, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 83 lines of Python from the credited upstream file design-in-memory-file-system.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123456 7class TrieNode(object):8 9 def __init__(self):10 self.is_file = False11 self.children = {}12 self.content = ""13 14class FileSystem(object):15 16 def __init__(self):17 self.__root = TrieNode()18 19 20 def ls(self, path):21 """22 :type path: str23 :rtype: List[str]24 """25 curr = self.__getNode(path)26 27 if curr.is_file:28 return [self.__split(path, '/')[-1]]29 30 return sorted(curr.children.keys())31 32 33 def mkdir(self, path):34 """35 :type path: str36 :rtype: void37 """38 curr = self.__putNode(path)39 curr.is_file = False40 41 42 def addContentToFile(self, filePath, content):43 """44 :type filePath: str45 :type content: str46 :rtype: void47 """48 curr = self.__putNode(filePath)49 curr.is_file = True50 curr.content += content51 52 53 def readContentFromFile(self, filePath):54 """55 :type filePath: str56 :rtype: str57 """58 return self.__getNode(filePath).content59 60 61 def __getNode(self, path):62 curr = self.__root63 for s in self.__split(path, '/'):64 curr = curr.children[s]65 return curr66 67 68 def __putNode(self, path):69 curr = self.__root70 for s in self.__split(path, '/'):71 if s not in curr.children:72 curr.children[s] = TrieNode()73 curr = curr.children[s]74 return curr75 76 77 def __split(self, path, delim):78 if path == '/':79 return []80 return path.split('/')[1:]81 82 83