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: returns True when path is an existing directory and False when it is an existing regular file (raises an error if path is missing).
  • list_dir(path: str) -> List[str]: returns the bare names (not full paths) of immediate entries inside directory path (raises an error if path is not a directory).
  • delete_file(path: str) -> None: removes one regular file (raises an error if path is missing or is a directory).
  • delete_directory(path: str) -> None: removes one directory only when zero entries remain inside it (raises an error if path is 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:

  1. Model the restricted storage primitives and remove root_path along with every file and subdirectory nested beneath it (leaving everything outside root_path untouched).
  2. 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.
  3. Return the chronological deletion log as "file:<path>" and "directory:<path>" strings.
  4. If root_path does not appear in files or directories, perform no deletions and return []. If root_path is 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_path names 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,000 levels (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

  1. Understand both the filesystem rules and the judge contract

    We want to remove root_path and everything nested inside it using only four low-level filesystem primitives:

    • is_directory(path) — returns True for a directory, False for 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:

    1. remove_tree(fs, root_path) — the core traversal algorithm written strictly against the four FileSystem primitives.
    2. InMemoryFileSystem + delete_tree(...) — a small adapter enforcing the empty-directory invariant and recording the judge's log.
  2. Why deletion requires post-order—and why recursion crashes

    Since delete_directory rejects any folder that still holds entries, every file and subfolder inside D has to vanish before D itself. 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,000 levels deep! Each nested call consumes one frame on Python's call stack, which defaults to roughly 1,000 frames and raises RecursionError long before depth 20,000.

  3. Key idea: simulate post-order with a two-visit explicit stack

    Instead of relying on Python's call stack, we maintain our own stack list in heap memory (which comfortably holds 100,000 entries).

    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):

    1. First visit (path, False):
      • If path is a regular file, call fs.delete_file(path) right away.
      • If path is a directory, push (path, True) back onto the stack first, and then push all its children (child_path, False) on top of it.
    2. 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 call fs.delete_directory(path)!

    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!)
    
  4. Write path joining and `remove_tree`

    list_dir(path) returns bare entry names like "env", so _join_path joins the parent directory and child name cleanly without creating "//a" when parent is "/". Notice also that if root_path points directly to a single file (Example 2), its very first pop hits not 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))
    
  5. Build `InMemoryFileSystem` and `delete_tree` for the judge

    To index the judge's files and directories lists, _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" in self.children["/srv/bin"].
    • Splitting at the rightmost "/" (rather than checking path.startswith(root_path)) ensures lookalike siblings such as "/srv2/x" or "/srv.bak" are never mistaken for children of "/srv".
    • delete_directory checks if 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:]
    
  6. Trace Example 1 step by step on the stack

    Let's watch remove_tree run 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.

  7. 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):

  1. 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.
  2. Pop ("/srv/bin", False), push ("/srv/bin", True) and ("/srv/bin/run.sh", False) on top; the next two pops remove run.sh and then the now-empty /srv/bin.
  3. Subsequent pops delete /srv/env and /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) for remove_tree (plus O(N + L_all) in the judge wrapper to index all N input paths). Every file under root_path is pushed and popped once, and every directory is pushed and popped twice (O(n) stack operations and O(n) filesystem calls). Sorting each directory's immediate child names costs O(c log c) for c children, which sums across all directories to at most O(n log n). Joining parent and child strings copies each path once, costing O(L) character operations.
  • Space: O(n + L) worst-case stack memory. At any moment, stack holds the ancestor directories along the active root-to-node path plus their unvisited sibling children. Even if a single flat directory holds 100,000 files, stack is a regular Python list on the heap rather than the call stack, using O(n) entries (O(L) total string characters) without any recursion-limit risk.

Edge cases

  • root_path is a regular file (Example 2): Popped once on (root_path, False), is_directory returns False, delete_file removes only that file, and its parent directory and siblings stay untouched.
  • root_path is an empty directory: First visit pushes (root_path, True) and zero children; second visit immediately calls delete_directory(root_path).
  • Nested empty directories (Example 3): Removed strictly bottom-up (/var/cache/old before /var/cache) while leaving sibling entries like /var/keep.txt untouched.
  • Lookalike path prefixes (/srv vs /srv2 or /srv.bak): Because children are determined by splitting at "/" (or calling fs.list_dir), deleting /srv never touches /srv2/y or /srv.bak.
  • Deep chain of 20,000 directories: Runs iteratively on the heap-allocated stack list with O(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_tree checks fs.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 missing root_path should be ignored or raise FileNotFoundError.

Common mistakes

  • Attempting pre-order deletion (directory before children): delete_directory immediately fails because the directory is still non-empty.
  • Using call-stack recursion: Hits CPython's 1,000-frame recursion limit well below the 20,000 depth 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 so delete_directory runs before the children are deleted! Always push (path, True) before pushing the children.
  • Passing bare child names straight to is_directory or delete_file: list_dir("/srv") returns ["env"], not ["/srv/env"]; forgetting _join_path looks up paths in the wrong place.
  • Blindly concatenating parent + "/" + name: Produces "//a" when parent == "/".

Alternative approaches

  • Two-stack post-order: Pop paths from stack_1, push each visited path onto stack_2, and push directory children onto stack_1 in forward sorted order; once stack_1 is empty, pop stack_2 to delete everything in reverse pre-order (which equals post-order). This avoids the boolean flag, though it holds all n paths in stack_2 before 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 only next(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; once StopIteration fires, every child is gone so call delete_directory(dir_path) and pop the frame. Working memory drops from O(total_items) to O(depth) active iterators (and if paginated backend iterators can skip entries when mutated mid-scan, do one final check with list_dir before delete_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_children counter initialized to 1 + child_count (the extra 1 guards against premature deletion while listing is still running), submit delete_file jobs for files and expansion jobs for subdirectories to the worker pool, and decrement remaining_children once listing completes. Each finished file deletion or child-directory deletion decrements its parent's counter; whichever worker brings a directory's counter down to 0 deletes 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, and delete_directory so FileNotFoundError is 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 from root_path, so simply re-invoking remove_tree from root_path finishes cleaning up whatever was left behind (and if concurrent writers can create new files mid-run, catch "not empty" on delete_directory by pushing (path, False) again to sweep the newcomers).

Follow-up questions

Similar questions

More Datadog interview questions

All 18 Datadog questions →