KatInterview

Remove Paths by Prefix Hierarchy

StringsModel answer
MediumModel answerStringstrieprefix-matchingstring-processing

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

  1. paths — a list of filesystem-like path strings (e.g., "docs", "docs/projects", "docs/projects/alpha")
  2. 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