All problems
0569MediumArrayStringDepth-First SearchTrie

Backup Roots Only

Tracked in this browser only
Write code

Trains the technique from

LeetCode 1233Remove Sub-Folders from the Filesystem

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A backup tool is handed a list of directory paths in folder, in no particular order. Each path starts with / and its directory names are separated by /, for example /store/rack/shelf names the directory shelf inside rack inside store.

A path is nested when another path in the list names one of its ancestor directories: /store/rack/shelf is nested when /store or /store/rack is also listed. Matching is by whole directory names, so /store/rackham is not nested inside /store/rack even though the text of one begins with the text of the other.

Backing up a directory covers everything under it, so the tool drops every nested path. Return the paths that survive, sorted in ascending lexicographic order by their characters.

Examples

Example 1

Input
folder = ["/store/rack", "/store/rackham", "/store/rack/shelf", "/store"]
Output
["/store"]

`/store` is listed, so `/store/rack` and `/store/rackham` are both nested inside it, and `/store/rack/shelf` is nested too. Only `/store` survives.

Example 2

Input
folder = ["/a/b", "/a/bc"]
Output
["/a/b", "/a/bc"]

Neither path names an ancestor of the other: `b` and `bc` are different directory names inside `/a`, and `/a` itself is not in the list.

Example 3

Input
folder = ["/p", "/p/q/r"]
Output
["/p"]

`/p` is an ancestor of `/p/q/r`, even though the directory `/p/q` between them is not listed, so the deeper path is dropped.

Constraints

  • 1 <= folder.length <= 4 * 10^4
  • 2 <= folder[i].length <= 100
  • folder[i] consists of lowercase English letters and '/'.
  • folder[i] starts with '/' and does not end with '/'.
  • All paths in folder are distinct.
  • The result is sorted in ascending lexicographic order.

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def remove_subfolders(folder: list[str]) -> list[str]:
Java
public List<String> removeSubfolders(String[] folder)
September 7
Apply