Emptying a Directory Tree: Record the Deletion Order
Trees & GraphsAuto-graded · 21 test casesLast updated
Produce the deterministic bottom-up deletion sequence for a file tree given as flat path lists, using an iterative post-order traversal that survives very deep nesting.
Wiping a Subtree Bottom-Up
A storage backend lets you remove files freely, but it refuses to remove a directory unless that directory is already empty. You want to wipe out everything at a given path, like rm -rf, and you need the exact order in which the removals happen.
The filesystem is described by two flat lists of path strings:
file_paths: entries that are regular files.dir_paths: entries that are directories.
Given target, return the ordered list of removal operations that deletes target and everything beneath it.
Output format
Each operation is a string:
"file:" + pathwhen a file is removed."directory:" + pathwhen a directory is removed.
Precise rules
Parent and name. Split a path string at its last /. The part before it is the parent string and the part after it is the name. If the parent string is empty (for example /a), the parent is "/". Paths are treated as literal strings, with no normalization. A directory d has as children exactly those entries whose parent string equals d character for character.
What counts as a file. A path is a file if and only if it appears in file_paths. Every other path, including a target that appears in neither list, is a directory. A file is always a leaf. If other entries have a file as their parent, they are never reached.
Entries. Every occurrence of a path in file_paths or dir_paths is one entry. If the same path occurs more than once, across or within the lists, each occurrence is a separate child entry and is processed separately. Processing it again emits its operations again, including those for its whole subtree. If a path occurs in both lists, it is a file.
Target. Every occurrence of target in the lists is ignored when building children, so target is never a child of anything. The traversal starts at target itself.
Reachability. Only entries reachable from target through the parent-to-child relation above are processed. A directory's parent does not need to be listed for the entry to be a child of it. Entries that are not reachable never appear in the output.
Order of removal.
- A directory is removed only after all of its children, and everything below them, have been removed.
- A file is removed as soon as it is reached.
- The children of a directory are processed in ascending order of their names (the last path component). Names are compared as plain Python strings, by Unicode code point. This is not the order of the full paths. A child's entire subtree is finished before the next sibling begins.
- If
targetis a file, the answer is the single operationfile:<target>. Iftargetis an empty directory (no children), the answer is the single operationdirectory:<target>. - If
targetis/, the top-level entries (those with parent"/") are its children.
Nesting can be extremely deep, so a solution that relies on ordinary recursion in Python will exceed the interpreter's recursion limit. Use an approach that does not depend on the call stack.
Constraints
- The total number of entries (files plus directories) is at most
100,000. - Nesting depth can reach
20,000. - Paths are absolute strings starting with
/, use/as the separator, and have no trailing slash (except the root/itself). targetmay be a file or a directory.
Examples
Example 1
Input: deletion_order([], ['/app', '/app/logs'], '/app')
Output: ['directory:/app/logs', 'directory:/app']
Example 2
Input: deletion_order(['/app/config.json'], ['/app'], '/app/config.json')
Output: ['file:/app/config.json']
Example 3
Input: deletion_order(['/tmp/a', '/tmp/z', '/tmp/logs/x'], ['/tmp', '/tmp/logs'], '/tmp')
Output: ['file:/tmp/a', 'file:/tmp/logs/x', 'directory:/tmp/logs', 'file:/tmp/z', 'directory:/tmp']
Hints
Hint 1
A directory can only go after everything inside it, so you need a post-order traversal: handle children first, then the node itself.
Hint 2
Python cannot recurse 20,000 levels deep. Simulate the call stack yourself, for example by pushing a (path, exiting) pair, and push the directory again with exiting=True before pushing its children.
Hint 3
Build a parent-to-children map by splitting each path at its last '/'; an empty parent means '/'. Skip entries equal to the target, and push children in reverse sorted name order so the smallest name pops first.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A directory may only be removed once it is empty, so every descendant must be removed before its ancestor. That is a post-order traversal.
Plain recursion would be the natural way to write it, but with depth up to 20,000 it would overflow Python's recursion limit. Instead, we keep our own stack on the heap.
- Build the child lists. For every entry other than
target, split the path at the last/withrpartition. The left part is the parent. If it is empty, the parent is/. Store(name, full_path)under that parent. This mimics what a directory listing would return. Duplicate entries are kept as separate entries. - Traverse with an explicit stack of
(path, leaving)pairs, starting with(target, False):- Pop
(path, True): all children are already gone, so recorddirectory:path. - Pop
(path, False)wherepathis in the file set: recordfile:path. A file is a leaf, so nothing is pushed. - Pop
(path, False)wherepathis anything else (a directory): push(path, True)first, then push its children as(child, False). Children are pushed in reverse sorted order, so the smallest name ends up on top and is popped first.
- Pop
Why it is correct
When (d, True) is pushed, all of d's children are pushed on top of it. Because the stack is LIFO, the marker cannot be popped until every child, together with everything those children push above the marker, has been fully processed. By induction on subtree height, each child's whole subtree is removed before d's marker pops, so every directory removal happens when the directory is empty.
Sorting each directory's children by name and pushing them in reverse gives ascending sibling order. The stack discipline finishes each subtree before the next sibling starts. Entries not reachable from target are never pushed, so they never appear in the output. A file target produces one entry, and an empty directory target produces only its own exit marker.
Complexity
With N total entries:
- Time: O(N log N). Building the map is O(N) (ignoring path length), and sorting the children of all directories costs O(N log N) in total. Each entry is pushed and popped a constant number of times.
- Space: O(N) for the set, the child map, the stack and the output. None of it uses the interpreter call stack.
Reference solution
from collections import defaultdict
from typing import List
def deletion_order(file_paths: List[str], dir_paths: List[str], target: str) -> List[str]:
file_set = set(file_paths)
# parent path -> list of (child name, child full path)
kids = defaultdict(list)
for p in file_paths + dir_paths:
if p == target:
continue
parent, _, name = p.rpartition("/")
if not parent:
parent = "/"
kids[parent].append((name, p))
ops = []
stack = [(target, False)] # (path, is_exit_marker)
while stack:
path, leaving = stack.pop()
if leaving:
ops.append("directory:" + path)
elif path in file_set:
ops.append("file:" + path)
else:
stack.append((path, True))
for _, child in sorted(kids[path], reverse=True):
stack.append((child, False))
return ops