Remove Sub-Folders from the Filesystem (LeetCode 1233): Solution and Explanation
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
- Sort
folderlexicographically. - Create an empty list
result. - For each path
fin sorted order, ifresultis empty orfdoes not start withresult[-1] + "/", appendftoresult. - Otherwise skip
f, because it lives insideresult[-1]. - Return
result.
Step-by-step example
folder = ["/a","/a/b","/c/d","/c/d/e","/c/f"]
- Sorting leaves the list unchanged: ["/a","/a/b","/c/d","/c/d/e","/c/f"].
- "/a": result is empty, so keep it. result = ["/a"].
- "/a/b" starts with "/a/", so it is a sub-folder. Skip.
- "/c/d" does not start with "/a/". Keep it. result = ["/a","/c/d"].
- "/c/d/e" starts with "/c/d/". Skip.
- "/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 result1class Solution {
2 public List<String> removeSubfolders(String[] folder) {
3 Arrays.sort(folder);
4 List<String> result = new ArrayList<>();
5 for (String f : folder) {
6 if (result.isEmpty() || !f.startsWith(result.get(result.size() - 1) + "/")) {
7 result.add(f);
8 }
9 }
10 return result;
11 }
12}1class Solution {
2public:
3 vector<string> removeSubfolders(vector<string>& folder) {
4 sort(folder.begin(), folder.end());
5 vector<string> result;
6 for (const string& f : folder) {
7 if (result.empty() || f.rfind(result.back() + "/", 0) != 0) {
8 result.push_back(f);
9 }
10 }
11 return result;
12 }
13};Time and space complexity
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.
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.