Subtree Deletion Using Restricted Filesystem Primitives
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Design an iterative subtree removal routine on top of a minimalist storage backend where non-empty directories cannot be removed.
On the storage backend, only four primitive operations are permitted:
is_directory(path: str) -> bool: returnsTruewhenpathis an existing directory andFalsewhen it is an existing regular file (raises an error ifpathis missing).list_dir(path: str) -> List[str]: returns the bare names (not full paths) of immediate entries inside directorypath(raises an error ifpathis not a directory).delete_file(path: str) -> None: removes one regular file (raises an error ifpathis missing or is a directory).delete_directory(path: str) -> None: removes one directory only when zero entries remain inside it (raises an error ifpathis missing or still contains any child file or subdirectory).
To verify your traversal deterministically, implement the entry point:
def delete_tree(files: List[str], directories: List[str], root_path: str) -> List[str]:
Given the initial regular file paths files, existing directory paths directories, and target root_path:
- Model the restricted storage primitives and remove
root_pathalong with every file and subdirectory nested beneath it (leaving everything outsideroot_pathuntouched). - Whenever expanding a directory, process its immediate child names in ascending lexicographical order, finishing each child's entire subtree before moving to the next sibling.
- Return the chronological deletion log as
"file:<path>"and"directory:<path>"strings. - If
root_pathdoes not appear infilesordirectories, perform no deletions and return[]. Ifroot_pathis a regular file, delete only that file and return["file:" + root_path].
Examples
Example 1
- Input:
files = ["/srv/readme.md", "/srv/bin/run.sh", "/srv/env"]directories = ["/srv", "/srv/bin"]root_path = "/srv"
- Output:
["file:/srv/bin/run.sh", "directory:/srv/bin", "file:/srv/env", "file:/srv/readme.md", "directory:/srv"] - Explanation: Immediate children of
"/srv"in alphabetical name order are"bin","env", and"readme.md". Entering"/srv/bin"deletes"run.sh"first so"/srv/bin"becomes empty and can be removed;"env"and"readme.md"are deleted next, leaving"/srv"empty for final removal.
Example 2
- Input:
files = ["/srv/readme.md", "/srv/env"]directories = ["/srv"]root_path = "/srv/env"
- Output:
["file:/srv/env"] - Explanation: Because
root_pathnames a single file, only"/srv/env"is removed while parent"/srv"and sibling"/srv/readme.md"stay intact.
Example 3
- Input:
files = ["/var/keep.txt"]directories = ["/var", "/var/cache", "/var/cache/old"]root_path = "/var/cache"
- Output:
["directory:/var/cache/old", "directory:/var/cache"] - Explanation: Empty inner directory
"/var/cache/old"is deleted before"/var/cache", while"/var"and"/var/keep.txt"outside"/var/cache"are untouched.
Constraints
0 <= len(files) + len(directories) <= 100,000- Directory nesting depth can reach
20,000levels (exceeding Python's default call-stack recursion limit). - Every path begins with
"/"and uses"/"between segments, with no trailing slash except for the filesystem root"/"itself. - Sibling paths that merely share a character prefix (such as
"/srv2"vs."/srv") are distinct entries and must not be treated as descendants.
Step-by-step walkthrough
Understand both the filesystem rules and the judge contract
We want to remove
root_pathand everything nested inside it using only four low-level filesystem primitives:is_directory(path)— returnsTruefor a directory,Falsefor a regular file.list_dir(path)— returns immediate child names (such as"bin", not"/srv/bin").delete_file(path)— removes one regular file.delete_directory(path)— removes a directory only when zero entries remain inside it (raises an error otherwise!).
Notice how the automated judge tests our algorithm: instead of passing a pre-built storage client, the judge calls
delete_tree(files, directories, root_path)with lists of full paths and verifies the exact sequence of deletions returned as"file:<path>"and"directory:<path>"strings.Example 1 directory tree: /srv ├── bin/ (directory) │ └── run.sh (file) ├── env (file) └── readme.md (file) Expected deletion log (children in alphabetical name order, bottom-up): 1. "file:/srv/bin/run.sh" 2. "directory:/srv/bin" <- now empty! 3. "file:/srv/env" 4. "file:/srv/readme.md" 5. "directory:/srv" <- now empty!So our solution cleanly separates two pieces:
remove_tree(fs, root_path)— the core traversal algorithm written strictly against the fourFileSystemprimitives.InMemoryFileSystem+delete_tree(...)— a small adapter enforcing the empty-directory invariant and recording the judge's log.
Why deletion requires post-order—and why recursion crashes
Since
delete_directoryrejects any folder that still holds entries, every file and subfolder insideDhas to vanish beforeDitself. In tree terminology, finishing every child subtree completely before acting on the parent node is a post-order traversal.Writing post-order recursively takes only a few lines:
def remove_tree_recursive(fs, path: str) -> None: if not fs.is_directory(path): fs.delete_file(path) return for name in sorted(fs.list_dir(path)): child_path = path + "/" + name if not path.endswith("/") else path + name remove_tree_recursive(fs, child_path) fs.delete_directory(path)That gives the right bottom-up order—until the folder hierarchy reaches
20,000levels deep! Each nested call consumes one frame on Python's call stack, which defaults to roughly1,000frames and raisesRecursionErrorlong before depth20,000.Key idea: simulate post-order with a two-visit explicit stack
Instead of relying on Python's call stack, we maintain our own
stacklist in heap memory (which comfortably holds100,000entries).How do we make a last-in, first-out (LIFO) stack delete a directory after its children? We push each directory onto the stack twice, pairing every path with a boolean
(path, children_deleted):- First visit
(path, False):- If
pathis a regular file, callfs.delete_file(path)right away. - If
pathis a directory, push(path, True)back onto the stack first, and then push all its children(child_path, False)on top of it.
- If
- Second visit
(path, True):- Because a stack pops from the top down,
(path, True)cannot surface again until every child (and grandchild) pushed above it has been popped and deleted. The folder is guaranteed empty, so callfs.delete_directory(path)!
- Because a stack pops from the top down,
Why do we push
sorted(fs.list_dir(path))in reverse order? Because a LIFO stack reverses push order: pushing"readme.md", then"env", then"bin"places"bin"at the top so"bin"is popped first!Expanding ("/srv", False) with sorted children ["bin", "env", "readme.md"]: Before pop: After pushing ("/srv", True) + reversed children: top -> ("/srv/bin", False) <- popped 1st! ("/srv/env", False) <- popped 2nd ("/srv/readme.md", False) <- popped 3rd top -> ("/srv", False) bottom -> ("/srv", True) <- popped last (now empty!)- First visit
Write path joining and `remove_tree`
list_dir(path)returns bare entry names like"env", so_join_pathjoins the parent directory and child name cleanly without creating"//a"whenparentis"/". Notice also that ifroot_pathpoints directly to a single file (Example 2), its very first pop hitsnot fs.is_directory(path), deletes that one file, and exits!from typing import Any, List, Tuple def _join_path(parent: str, child_name: str) -> str: """Join a directory path and an immediate child name without double slashes.""" if parent.endswith("/"): return parent + child_name return parent + "/" + child_name def remove_tree(fs: Any, root_path: str) -> None: """Delete root_path and all descendants using only the four FileSystem primitives.""" stack: List[Tuple[str, bool]] = [(root_path, False)] while stack: path, children_deleted = stack.pop() if children_deleted: fs.delete_directory(path) elif not fs.is_directory(path): fs.delete_file(path) else: stack.append((path, True)) child_names = sorted(fs.list_dir(path)) for name in reversed(child_names): child_path = _join_path(path, name) stack.append((child_path, False))Build `InMemoryFileSystem` and `delete_tree` for the judge
To index the judge's
filesanddirectorieslists,_split_parent_and_name(path)splits each full path at its rightmost"/"into(parent_dir, child_name):"/srv/bin/run.sh"splits into("/srv/bin", "run.sh"), registering"run.sh"inself.children["/srv/bin"].- Splitting at the rightmost
"/"(rather than checkingpath.startswith(root_path)) ensures lookalike siblings such as"/srv2/x"or"/srv.bak"are never mistaken for children of"/srv". delete_directorychecksif self.children[path]: raise OSError(...), proving our traversal never deletes a non-empty folder.
from typing import Dict, List, Optional, Set, Tuple def _split_parent_and_name(path: str) -> Tuple[Optional[str], str]: """Split '/a/b' -> ('/a', 'b'), '/a' -> ('/', 'a'), and '/' -> (None, '').""" if path == "/": return None, "" slash_index = path.rfind("/") if slash_index == -1: return None, path if slash_index == 0: return "/", path[1:] return path[:slash_index], path[slash_index + 1:]Trace Example 1 step by step on the stack
Let's watch
remove_treerun on Example 1 (files = ['/srv/readme.md', '/srv/bin/run.sh', '/srv/env'],directories = ['/srv', '/srv/bin'],root_path = '/srv'). Below, the right-hand end of the list is the top of the stack:Initial stack: [("/srv", False)] 1. Pop ("/srv", False) -> directory! Push ("/srv", True), then reversed ["bin", "env", "readme.md"]: stack: [("/srv", True), ("/srv/readme.md", False), ("/srv/env", False), ("/srv/bin", False)] 2. Pop ("/srv/bin", False) -> directory! Push ("/srv/bin", True), then ["run.sh"]: stack: [("/srv", True), ("/srv/readme.md", False), ("/srv/env", False), ("/srv/bin", True), ("/srv/bin/run.sh", False)] 3. Pop ("/srv/bin/run.sh", False) -> file! Delete -> log: ["file:/srv/bin/run.sh"] stack: [("/srv", True), ("/srv/readme.md", False), ("/srv/env", False), ("/srv/bin", True)] 4. Pop ("/srv/bin", True) -> children_deleted is True! Delete -> log: [..., "directory:/srv/bin"] stack: [("/srv", True), ("/srv/readme.md", False), ("/srv/env", False)] 5. Pop ("/srv/env", False) -> file! Delete -> log: [..., "file:/srv/env"] stack: [("/srv", True), ("/srv/readme.md", False)] 6. Pop ("/srv/readme.md", False) -> file! Delete -> log: [..., "file:/srv/readme.md"] stack: [("/srv", True)] 7. Pop ("/srv", True) -> children_deleted is True! Delete -> log: [..., "directory:/srv"] stack: [] (done!)Every child entry was deleted before its enclosing directory, matching Example 1 item for item.
Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def _join_path(parent: str, child_name: str) -> str: """Join a directory path and an immediate child name without double slashes.""" # When parent is the root "/", avoid producing "//child_name". if parent.endswith("/"): return parent + child_name return parent + "/" + child_name def _split_parent_and_name(path: str) -> Tuple[Optional[str], str]: """Split '/a/b' -> ('/a', 'b'), '/a' -> ('/', 'a'), and '/' -> (None, '').""" if path == "/": return None, "" slash_index = path.rfind("/") if slash_index == -1: return None, path if slash_index == 0: return "/", path[1:] return path[:slash_index], path[slash_index + 1:] def remove_tree(fs: Any, root_path: str) -> None: """Delete root_path and all descendants using only the four FileSystem primitives.""" # stack: LIFO list of (path, children_deleted) tuples simulating post-order DFS. # children_deleted == False -> first visit: delete file, or expand directory children. # children_deleted == True -> second visit: all descendants are gone, delete directory. stack: List[Tuple[str, bool]] = [(root_path, False)] while stack: path, children_deleted = stack.pop() if children_deleted: # Second visit: every child pushed above this frame has already been popped and deleted. fs.delete_directory(path) elif not fs.is_directory(path): # Base case: regular files have no children and can be deleted immediately. fs.delete_file(path) else: # First visit to a directory: push its second-visit frame FIRST so it stays below its children. stack.append((path, True)) # Sort child names ascending, then push in reverse so the smallest name sits on top of the stack. child_names = sorted(fs.list_dir(path)) for name in reversed(child_names): child_path = _join_path(path, name) stack.append((child_path, False)) class InMemoryFileSystem: """Adapter implementing the 4-method FileSystem contract and recording deletions for the judge.""" def __init__(self, files: List[str], directories: List[str]): # files: set of active file paths, e.g. {"/srv/env", "/srv/bin/run.sh"} # directories: set of active directory paths, e.g. {"/srv", "/srv/bin"} self.files: Set[str] = set(files) self.directories: Set[str] = set(directories) # children: dict mapping directory_path -> set of immediate child names, e.g. {"/srv": {"bin", "env", "readme.md"}} self.children: Dict[str, Set[str]] = {} for directory_path in self.directories: self.children[directory_path] = set() for path in self.files | self.directories: parent, name = _split_parent_and_name(path) if parent in self.children: self.children[parent].add(name) # log: ordered list of deletion operations formatted as "file:<path>" or "directory:<path>" self.log: List[str] = [] def exists(self, path: str) -> bool: return path in self.files or path in self.directories def is_directory(self, path: str) -> bool: if path in self.directories: return True if path in self.files: return False raise FileNotFoundError(path) def list_dir(self, path: str) -> List[str]: if path not in self.directories: raise NotADirectoryError(path) return list(self.children[path]) def delete_file(self, path: str) -> None: if path not in self.files: raise FileNotFoundError(path) self.files.remove(path) self._detach_from_parent(path) self.log.append("file:" + path) def delete_directory(self, path: str) -> None: if path not in self.directories: raise FileNotFoundError(path) # Enforce the core filesystem invariant: non-empty directories cannot be deleted. if self.children[path]: raise OSError("Directory is not empty: " + path) self.directories.remove(path) del self.children[path] self._detach_from_parent(path) self.log.append("directory:" + path) def _detach_from_parent(self, path: str) -> None: parent, name = _split_parent_and_name(path) if parent in self.children: self.children[parent].discard(name) def delete_tree(files: List[str], directories: List[str], root_path: str) -> List[str]: """Judge entry point: construct the filesystem, run remove_tree, and return the deletion log.""" fs = InMemoryFileSystem(files, directories) # Like `rm -rf`, a non-existent target path is a safe no-op with nothing to delete. if not fs.exists(root_path): return [] remove_tree(fs, root_path) return fs.log✅ Submit now — all tests should pass.
Intuition & how it works
Imagine unpacking and recycling a tall tower of nested cardboard boxes where house rules forbid crushing any box while something still sits inside it. You cannot toss the outer /srv box first; you have to open it, clear out every inner box completely, and only come back to toss /srv at the very end. In computer science, processing every child subtree completely before acting on the parent node is called a post-order traversal. To keep our place across 20,000 nested levels without blowing up recursion limits, we maintain an explicit LIFO stack (a last-in, first-out list where the newest item added is popped first) of (path, children_deleted) pairs: False means "inspect or unpack this path", and True means "every descendant is already gone—remove this empty directory now!"
Two obvious shortcuts break immediately. Trying to remove directories top-down fails because delete_directory raises an error whenever a folder still has children. Writing a plain recursive function visits nodes in the right bottom-up order, yet every nested folder consumes one frame on Python's call stack (the fixed-depth internal stack tracking active function calls, capped around 1,000 frames by default in CPython), triggering RecursionError on a 20,000-deep directory chain.
Here is how the explicit two-visit stack executes on Example 1 (/srv containing /srv/bin/run.sh, /srv/env, and /srv/readme.md):
- Start with
[("/srv", False)]. Pop it, see a directory, push("/srv", True)first, and push its reversed sorted children("/srv/readme.md", False),("/srv/env", False), and("/srv/bin", False)above it. - Pop
("/srv/bin", False), push("/srv/bin", True)and("/srv/bin/run.sh", False)on top; the next two pops removerun.shand then the now-empty/srv/bin. - Subsequent pops delete
/srv/envand/srv/readme.md, exposing("/srv", True)at the bottom to delete the now-empty/srv.
Complexity
Let n be the number of files and directories inside root_path, and L be the sum of the character lengths of their path strings.
- Time:
O(n log n + L)forremove_tree(plusO(N + L_all)in the judge wrapper to index allNinput paths). Every file underroot_pathis pushed and popped once, and every directory is pushed and popped twice (O(n)stack operations andO(n)filesystem calls). Sorting each directory's immediate child names costsO(c log c)forcchildren, which sums across all directories to at mostO(n log n). Joining parent and child strings copies each path once, costingO(L)character operations. - Space:
O(n + L)worst-case stack memory. At any moment,stackholds the ancestor directories along the active root-to-node path plus their unvisited sibling children. Even if a single flat directory holds100,000files,stackis a regular Python list on the heap rather than the call stack, usingO(n)entries (O(L)total string characters) without any recursion-limit risk.
Edge cases
root_pathis a regular file (Example 2): Popped once on(root_path, False),is_directoryreturnsFalse,delete_fileremoves only that file, and its parent directory and siblings stay untouched.root_pathis an empty directory: First visit pushes(root_path, True)and zero children; second visit immediately callsdelete_directory(root_path).- Nested empty directories (Example 3): Removed strictly bottom-up (
/var/cache/oldbefore/var/cache) while leaving sibling entries like/var/keep.txtuntouched. - Lookalike path prefixes (
/srvvs/srv2or/srv.bak): Because children are determined by splitting at"/"(or callingfs.list_dir), deleting/srvnever touches/srv2/yor/srv.bak. - Deep chain of 20,000 directories: Runs iteratively on the heap-allocated
stacklist withO(1)Python call-stack frames. - Root directory
"/":_join_path("/", "a")avoids producing"//a", and_split_parent_and_name("/")returns(None, "")so"/"never registers itself as its own child. - Missing
root_path:delete_treechecksfs.exists(root_path)and returns[]as a safe no-op; in an interview with a live storage client, mention that you would confirm whether a missingroot_pathshould be ignored or raiseFileNotFoundError.
Common mistakes
- Attempting pre-order deletion (directory before children):
delete_directoryimmediately fails because the directory is still non-empty. - Using call-stack recursion: Hits CPython's
1,000-frame recursion limit well below the20,000depth constraint. - Pushing sorted children in forward order instead of reverse: Because a stack is LIFO, pushing
["bin", "env", "readme.md"]in forward order puts"readme.md"on top and deletes"readme.md"first instead of"bin". - Pushing
(path, True)after pushing children: Places(path, True)on top of its children sodelete_directoryruns before the children are deleted! Always push(path, True)before pushing the children. - Passing bare child names straight to
is_directoryordelete_file:list_dir("/srv")returns["env"], not["/srv/env"]; forgetting_join_pathlooks up paths in the wrong place. - Blindly concatenating
parent + "/" + name: Produces"//a"whenparent == "/".
Alternative approaches
- Two-stack post-order: Pop paths from
stack_1, push each visited path ontostack_2, and push directory children ontostack_1in forward sorted order; oncestack_1is empty, popstack_2to delete everything in reverse pre-order (which equals post-order). This avoids the boolean flag, though it holds allnpaths instack_2before performing the very first delete.
Follow-up questions
- Suppose directory listing yields entries lazily via an iterator so directories with millions of children fit in memory—how would you adapt your stack? Store
(dir_path, child_iterator)frames on the stack instead of materializing and pushing all children at once, advancing onlynext(child_iterator)on each loop step. If the yielded entry is a file, delete it immediately; if it is a subdirectory, leave the parent's paused iterator on the stack and push(child_path, iter(fs.list_dir(child_path)))above it; onceStopIterationfires, every child is gone so calldelete_directory(dir_path)and pop the frame. Working memory drops fromO(total_items)toO(depth)active iterators (and if paginated backend iterators can skip entries when mutated mid-scan, do one final check withlist_dirbeforedelete_directory). - How could you dispatch deletions across a bounded worker pool while still guaranteeing every child finishes before its parent directory is removed? Give each directory an atomic
remaining_childrencounter initialized to1 + child_count(the extra1guards against premature deletion while listing is still running), submitdelete_filejobs for files and expansion jobs for subdirectories to the worker pool, and decrementremaining_childrenonce listing completes. Each finished file deletion or child-directory deletion decrements its parent's counter; whichever worker brings a directory's counter down to0deletes that now-empty directory and decrements its grandparent's counter. Because workers never block waiting on child futures, deep trees cannot starve or deadlock the pool. - How would you make tree removal safe to retry and idempotent if the client crashes or loses connectivity partway through? An operation is idempotent when repeating it produces the exact same end state as a single clean run without failing. Wrap
is_directory,delete_file, anddelete_directorysoFileNotFoundErroris treated as "already removed (success)". Because post-order never deletes an ancestor directory before its contents, any surviving entries after an interrupted run remain reachable fromroot_path, so simply re-invokingremove_treefromroot_pathfinishes cleaning up whatever was left behind (and if concurrent writers can create new files mid-run, catch "not empty" ondelete_directoryby pushing(path, False)again to sweep the newcomers).
Follow-up questions
- Suppose directory listing yields entries lazily via an iterator so directories with millions of children fit in memory—how would you adapt your stack?
- How could you dispatch deletions across a bounded worker pool while still guaranteeing every child finishes before its parent directory is removed?
- How would you make tree removal safe to retry and idempotent if the client crashes or loses connectivity partway through?
Similar questions
- Reconstruct Call Trees from Shuffled Spans
- Windowed Metric Sums Filtered by Tag
- End-to-End Technical Project Walkthrough
- Improving Brevity After Communication Feedback
- Production Image Object Detection Service
- Autonomous LLM Coding Agent for Issue-to-PR Resolution
More Datadog interview questions
- Asynchronous Warehouse Query Client Medium
- Reconstruct Call Trees from Shuffled Spans Medium
- Grouped-Query Attention Forward Pass Hard Pro
- Online Keyword Query Matching Over Log Streams Medium Pro
- Windowed Metric Sums Filtered by Tag Medium Pro
- End-to-End Technical Project Walkthrough Medium Pro
- Improving Brevity After Communication Feedback Medium Pro
- Autonomous LLM Coding Agent for Issue-to-PR Resolution Medium Pro
- Production Image Object Detection Service Hard Pro
- Real-Time Log and Query Stream Matcher Hard Pro