Design an in-memory file system
medium 85 minDesign directories and files that live in memory: create, read, write, list, move and remove by path.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Paths come in, nodes change. Watch the walk, the place and the two directions of each link.
Operations
Resolve a path
From text to a node, one part at a time, with a clear reason when it fails.
Step 1 of 6
Split
/trips/./sun/../sun becomes trips, sun, dot dot, sun. The walk starts at the root.
Step 1: Split
def _walk(self, parts, path): node = self._root for part in parts: if not isinstance(node, Directory): raise FsError(Kind.NOT_A_DIRECTORY, path) if part == "..": node = node.parent or node continue node = node.child(part) if node is None: raise FsError(Kind.NOT_FOUND, path) return node- Cost
- O(depth)
- Guarantee
- No search
- Map per directory
- 1 look a part
- List of children
- a search a part
Ask for the kind before you take the step.
In the real world
The same in-memory file system doing real jobs. Pick one and step through it.
Both checks are true when they are made. Together they destroy the tree.
Step 1 of 5
Start
The root holds a and b. Two threads begin.
Step 1: Start
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Detach before the last check
criticalThe target name is taken, an error is raised, and the node is in no directory.
Wrongold_parent.detach(node)new_parent.attach(node) # may refuseRightif new_parent.child(name) is not None: raise FsError(Kind.EXISTS, target)old_parent.detach(node)new_parent.attach(node)Containment by text
critical/abstarts with/aand is not below it./x/../a/bis below/aand does not start with it.Wrongif target.startswith(source): raise ...Rightstep = new_parentwhile step is not None: if step is node: raise FsError(Kind.INTO_ITSELF, target) step = step.parentFull paths in nodes
majorA rename must rewrite all below. One is forgotten, and nobody notices for a week.
Wrongnode.path = "/trips/sun/hat"Rightnode.name = "hat" # the path is computed by climbingOne direction only
criticalThe directory knows the child, the child has the old parent. Dot dot goes to the wrong place.
Wrongparent.children[name] = nodeRightparent.attach(node) # writes bothDot dot as text
majorA missing directory is hidden, and a link leads elsewhere.
Wrongpath = re.sub(r"/[^/]+/\.\.", "", path)Rightif part == "..": node = node.parent or nodeOne answer for all problems
minorThe caller cannot tell a typing error from a taken name.
Wrongreturn NoneRightraise FsError(Kind.NOT_A_DIRECTORY, path)
Interview tips
Open with
- A path is text.
- A node is a thing.
- One class knows both.
For each call
- Node or place?
- What does it refuse?
- Then the change.
Prove it
- move /a /a/b
- move /a /ab
- Unchanged after a refusal.
Never
- isDirectory flags.
- Stored paths.
- Null for everything.