Remove Paths by Prefix Hierarchy
StringsModel answerLast updated
Remove all paths that match or fall under any deletion target in a hierarchical filesystem-like structure.
You're building a filesystem cleanup utility. You have two lists of hierarchical paths:
paths— a list of filesystem-like path strings (e.g.,"docs","docs/projects","docs/projects/alpha")deletes— a list of paths marking directories to remove
Your task is to filter out every path that either matches a deletion target or is nested under one. Return the surviving paths.
Hierarchy rules:
- Paths are
/-delimited strings where each segment represents a directory level - A path is "under" another if it starts with all the parent's segments in order
- Matching happens on full segments, not partial strings:
"docs/pro"does not match"docs/projects"
Normalization:
- Leading, trailing, and consecutive slashes should be ignored:
"/docs/","docs", and"//docs//"all represent the same path - Empty paths (empty string or just slashes) should be ignored in the deletion list
Constraints:
- Both lists may contain duplicates (keep duplicates in output if they survive)
- Output order can match input order or any stable ordering
- Both lists can be empty
- 0 ≤ len(paths), len(deletes) ≤ 10⁴
- Path length ≤ 1000 characters
Examples:
Input:
paths = ["docs", "docs/projects", "docs/projects/alpha", "docs/drafts", "media"]
deletes = ["docs/projects"]
Output:
["docs", "docs/drafts", "media"]
Input:
paths = ["a/b/c", "a/b", "a/bc"]
deletes = ["a/b"]
Output:
["a/bc"]
(Note: "a/b/c" is removed because it's under "a/b", but "a/bc" survives because "bc" ≠ "b")
Implement an efficient solution that handles large inputs well. Explain your approach, complexity, and how you handle edge cases.
Hints
Hint 1
Think about how to efficiently check if one path is a prefix of another at the segment level
Hint 2
A trie structure can help you organize deletion targets and check membership quickly
Hint 3
Consider normalizing paths first by splitting on '/' and filtering out empty segments
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Approach
The core challenge is efficiently determining whether each path should be filtered based on segment-level prefix matching. The key insight is that a path survives only if no deletion target is a segment-wise prefix of that path.
Trie-Based Solution:
Build a trie indexed by path segments where each deletion target is inserted. Mark nodes that represent complete deletion paths. Then, for each input path, walk its segments down the trie:
- If we hit a marked node, this path is deleted (it equals or descends from a deletion target)
- If we can't continue (missing child), no deletion target can be a prefix — keep the path
- If we exhaust all segments without hitting a marked node, the path is an ancestor or unrelated — keep it
Optimization — Pruning Overlapping Deletes:
When inserting a deletion path, if we encounter an already-marked ancestor node, we can stop early (this deletion is redundant). Conversely, when marking a node, we can clear its children (any longer deletions are now redundant). This ensures the trie stores only the minimal set of deletions.
Why This Works
Correctness relies on segment-level matching:
- Splitting on
/and filtering empty strings handles all normalization (leading/trailing/double slashes) - Dictionary key lookups match entire segments, preventing partial matches like
"pro"matching"projects" - A marked trie node represents a complete deletion path, and reaching it during traversal means the current path is either equal to or nested under that deletion
Complexity Analysis
Let P = total characters across all paths, D = total characters across all deletes, n = len(paths), m = len(deletes).
Time: O(P + D)
- Splitting all paths: O(P)
- Building the trie: O(D), with each segment requiring one hash lookup
- Filtering: O(P), walking each path's segments through the trie
- Pruning only reduces work, never increases it
Space: O(D)
- The trie stores at most all segments from deletes (often fewer due to pruning)
- Output list is O(surviving paths)
- Temporary segment lists are O(max path depth)
Alternative Approach — Sorting:
Sort both lists after converting to segment tuples, then sweep through paths while maintaining a pointer to the current deletion range. This achieves O((n+m) log(n+m)) time but loses input order unless you track indices. The trie approach is faster for large inputs and preserves order naturally.
Edge Cases
| Scenario | Handling |
|---|---|
Empty paths | Return [] immediately |
Empty deletes | Return all paths (trie is empty, all checks return false) |
| Duplicate paths | Each instance is checked independently; duplicates survive if none match deletions |
| Overlapping deletes | Pruning ensures only minimal deletions are stored; behavior is correct regardless |
| Trailing/leading slashes | Normalized away during splitting |
"a/b" vs "a/bc" | Treated as different branches (segment "b" ≠ "bc") |
| Path is ancestor of deletion | Kept (walk completes without hitting marked node) |
| Empty string in deletes | Ignored (produces empty segment list) |
Implementation
from typing import List
_TERMINAL = object() # sentinel marking a deletion endpoint
def filter_paths(paths: List[str], deletes: List[str]) -> List[str]:
"""
Remove paths that match or are nested under any deletion target.
Matching is done at the segment level (full directory names).
"""
def parse_segments(path: str) -> List[str]:
"""Split path and remove empty segments from slashes."""
return [seg for seg in path.split('/') if seg]
# Build pruned trie of deletion targets
trie_root = {}
for delete_path in deletes:
segments = parse_segments(delete_path)
if not segments: # ignore empty deletions
continue
node = trie_root
already_deleted = False
for segment in segments:
if _TERMINAL in node: # ancestor already marked for deletion
already_deleted = True
break
node = node.setdefault(segment, {})
if not already_deleted:
# Mark this node as a deletion point and clear descendants
node.clear()
node[_TERMINAL] = True
def should_remove(path: str) -> bool:
"""Check if path matches or is under any deletion target."""
segments = parse_segments(path)
node = trie_root
for segment in segments:
if _TERMINAL in node: # we've matched a deletion target
return True
if segment not in node: # diverged from all deletions
return False
node = node[segment]
return False # path is ancestor or unrelated
return [path for path in paths if not should_remove(path)]
# Test cases
if __name__ == "__main__":
# Basic case
result = filter_paths(
["docs", "docs/projects", "docs/projects/alpha", "docs/drafts", "media"],
["docs/projects"]
)
assert result == ["docs", "docs/drafts", "media"]
# Segment boundary test
result = filter_paths(["a/b/c", "a/b", "a/bc"], ["a/b"])
assert result == ["a/bc"]
# Empty cases
assert filter_paths([], ["anything"]) == []
assert filter_paths(["a", "b"], []) == ["a", "b"]
# Normalization
result = filter_paths(
["docs/", "/docs/projects", "docs//archive"],
["/docs/projects/", "docs/archive"]
)
assert result == ["docs/"]
print("All tests passed!")
What Strong Candidates Demonstrate
- Immediate recognition that character-based
startswith()is incorrect and articulation of why segment-level matching matters - Choosing the right data structure (trie) and explaining the trade-off vs. sorting approaches
- Proactive normalization by splitting and filtering, with explicit handling of edge cases
- Optimization awareness through pruning redundant deletions
- Clear complexity analysis with concrete definitions of input size variables
- Testing mindset by walking through boundary cases like partial segment matches, empty inputs, and duplicates
Common mistakes to avoid:
- Using string prefix matching without segment boundaries
- O(n·m) brute force without considering scalability
- Forgetting to normalize slashes
- Not handling empty paths or empty deletion lists
- Assuming deletion list is minimal (overlapping deletes must be handled)