Remove Sub-Folders from the Filesystem (LeetCode 1233): Solution and Explanation

Medium
Array
String
Depth First Search
Trie

Given a list of folder paths, delete every folder that sits inside another folder of the list and return the remaining top-level folders in any order.

Intuition

Checking every pair of folders works but costs O(n^2) prefix tests, which is too slow for 40,000 paths.

Sorting the paths as plain strings changes the picture. A folder is a prefix of each of its sub-folders, so it sorts before them. Every path that starts with "/a/" also sorts after "/a" and before anything that does not share that prefix, so the sub-folders of a folder form one unbroken run directly after it.

That means a sorted scan only ever needs to remember one folder: the last one it kept. If the current path starts with that folder followed by a slash, it is a sub-folder and is dropped. If not, the run of sub-folders is over and the current path is a new top-level folder.

The slash matters. "/a/bc" starts with "/a/b" but is a different folder, so the test must be against "/a/b/", not "/a/b".

Approach: Sort, then compare with the last kept folder

  1. Sort folder lexicographically.
  2. Create an empty list result.
  3. For each path f in sorted order, if result is empty or f does not start with result[-1] + "/", append f to result.
  4. Otherwise skip f, because it lives inside result[-1].
  5. Return result.

Step-by-step example

folder = ["/a","/a/b","/c/d","/c/d/e","/c/f"]
  1. Sorting leaves the list unchanged: ["/a","/a/b","/c/d","/c/d/e","/c/f"].
  2. "/a": result is empty, so keep it. result = ["/a"].
  3. "/a/b" starts with "/a/", so it is a sub-folder. Skip.
  4. "/c/d" does not start with "/a/". Keep it. result = ["/a","/c/d"].
  5. "/c/d/e" starts with "/c/d/". Skip.
  6. "/c/f" does not start with "/c/d/". Keep it. The answer is ["/a","/c/d","/c/f"].

Code: Python, Java, C++

1class Solution:
2    def removeSubfolders(self, folder: List[str]) -> List[str]:
3        folder.sort()
4        result = []
5        for f in folder:
6            if not result or not f.startswith(result[-1] + "/"):
7                result.append(f)
8        return result
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n L log n)

Sorting n strings of length up to L takes O(n log n) comparisons of O(L) each. The scan does one O(L) prefix test per path.

Space

O(n L)

The result list and the sort's working space hold up to n paths.

Other approaches

Trie of path segments (time O(n L), space O(n L))

Split every path on '/' and insert the segments into a trie, marking the node where each folder ends. Then walk the trie depth first, and whenever you reach a marked node, record that folder and do not descend further. This avoids sorting.

Hash set of folders (time O(n L^2) with string hashing, space O(n L))

Put every path in a set. For each path, check each of its proper ancestor prefixes (cut at every '/') against the set, and keep the path only if none is present.

Common mistakes

  • Testing f.startswith(result[-1]) without the trailing slash, which wrongly removes "/a/bc" when "/a/b" is kept.
  • Comparing with the previous path in sorted order instead of the last kept one. After "/a", "/a/b", the path "/a/b/c" must still be compared with "/a".
  • Relying on a locale-aware sort. Use plain ordinal string order so '/' sorts before the letters.
  • Forgetting that input order is arbitrary: a sub-folder can come before its parent until you sort.

Frequently asked questions

Why is it enough to compare with only the last kept folder?

After sorting, all paths inside a kept folder X appear in one contiguous block right after X. Once a path that does not start with X + '/' appears, no later path can be inside X, so X never needs to be checked again.

Why does '/' need to be appended before the prefix test?

Folder names are whole segments. "/a/bc" shares the characters "/a/b" with "/a/b" but is a sibling, not a child. Adding the slash forces the match to end exactly at a segment boundary.

Is the trie solution faster in practice?

It removes the log n factor from sorting, but it allocates a node per segment. For inputs of this size both run quickly, and the sort version is shorter to write.