Suppose we have to design a file system which provides these two functions −
- createPath(path, value) − This creates a new path and associates a value to it if possible and returns True. It returns False if the path already exists or its parent path doesn't exist.
- get(path) − This finds the value associated with a path or returns -1 if the path doesn't exist.
The format of a path is one or more concatenated strings of the form − (forward slash) / followed by one or more lowercase English letters. For example, /programming and /programming/problems are valid paths while an empty string and / are not. Here we have to implement these two functions.
So as input, if we create a file-system, then create a path using [‘/a’, 1], then after using get(), with parameter [‘/a’], the output will be 1.
To solve this, we will follow these steps −
- Define a map d
- The createPath method will take path and value, this will act like −
- p := list of components of path split by ‘/’
- x := d
- for i in range 1 to length of p – 1
- if p[i] is not present in x, then return false
- x := x[p[i]][1]
- if last element of p is in x, then return false
- x[last element of p] := a list with v and empty map
- return true
- The get() method is taking the path
- x := d
- p := list of components of path split by ‘/’
- for i in range 1 to length of p – 1
- if p[i] is not present in x, then return -1
- x := x[p[i]][1]
- if last element of p is in x, then return x[last element of p][0], otherwise return -1
Example(Python)
Let us see the following implementation to get a better understanding −
class FileSystem(object): def __init__(self): self.d = {} def create(self, p, v): p = p.split("/") x = self.d for i in range(1,len(p)-1): if p[i] not in x: return False x = x[p[i]][1] if p[-1] in x: return False x[p[-1]] = [v,{}] return True def get(self, p): x = self.d p = p.split("/") for i in range(1,len(p)-1): if p[i] not in x: return -1 x= x[p[i]][1] if p[-1] in x: return x[p[-1]][0] else: return -1 ob = FileSystem() print(ob.create("/a", 1)) print(ob.get("/a"))
Input
Initialize the object, then call createPath(“/a”, 1) and get(“/a”)
Output
True 1