Intuition
- Check if the path prior to what you are placing is in your hashmap. If it is not, then you would be invalid.
- So this question relies mostly on the hashmap and making sure what leads up to the tail of your path is previously in your hashmap.
Runtime
- CreatePath: where W is the length of the string.
- get: through a hashmap search
Code
Hashmap Solution
class FileSystem:
def __init__(self):
self.hm = {}
def createPath(self, path: str, value: int) -> bool:
if path in self.hm:
return False
split = path.split("/")
root = "/".join(split[:-1])
if root != "" and root not in self.hm:
return False
tail = split[-1]
self.hm[f"{root}/{tail}"] = value
return True
def get(self, path: str) -> int:
if path in self.hm:
return self.hm[path]
return -1References
https://leetcode.com/problems/design-file-system/description/