Remove Sub-Folders from the Filesystem Problem
Description
LeetCode Problem 1233.
Given a list of folders folder, return the folders after removing all sub-folders in those folders. You may return the answer in any order.
If a folder[i] is located within another folder[j], it is called a sub-folder of it. A sub-folder of folder[j] must start with folder[j], followed by a "/". For example, "/a/b" is a sub-folder of "/a", but "/b" is not a sub-folder of "/a/b/c".
The format of a path is one or more concatenated strings of the form: '/' followed by one or more lowercase English letters.
- For example,
"/leetcode"and"/leetcode/problems"are valid paths while an empty string and"/"are not.
Example 1:
Input: folder = ["/a","/a/b","/c/d","/c/d/e","/c/f"]
Output: ["/a","/c/d","/c/f"]
Explanation: Folders "/a/b" is a subfolder of "/a" and "/c/d/e" is inside of folder "/c/d" in our filesystem.
Example 2:
Input: folder = ["/a","/a/b/c","/a/b/d"]
Output: ["/a"]
Explanation: Folders "/a/b/c" and "/a/b/d" will be removed because they are subfolders of "/a".
Example 3:
Input: folder = ["/a/b/c","/a/b/ca","/a/b/d"]
Output: ["/a/b/c","/a/b/ca","/a/b/d"]
Constraints:
1 <= folder.length <= 4 * 10^42 <= folder[i].length <= 100folder[i]contains only lowercase letters and'/'.folder[i]always starts with the character'/'.- Each folder name is unique.
Solution
Approach: Sort, Then Compare With the Last Kept Folder
Comparing every pair of folders takes O(n2) prefix tests, too slow for 4 * 10^4 folders. Sorting the paths as strings puts things in a convenient order: a folder comes before everything inside it, and everything that starts with "/a/b/" forms one contiguous block right after "/a/b".
So we walk the sorted list and keep a list of answers. For each folder f, let last be the most recently kept folder:
- If
fstarts withlast + "/", it is insidelastand is dropped. - Otherwise
fis not inside any kept folder and is kept.
Comparing only with last is enough. If f were inside some earlier kept folder p, then every path between p and f in sorted order also starts with p + "/", so all of them were dropped and last would still be p.
The "/" matters: "/a/bc" starts with "/a/b" but is not inside it, while "/a/b/c" is. Checking for the prefix last + "/" gets both right.
Complexity: O(n · m · log n) time for n folders of length up to m (the sort dominates), and O(n · m) space for the answer.
class Solution:
def removeSubfolders(self, folder: List[str]) -> List[str]:
folder.sort() # every sub-folder now comes right after its parent's group
ans = []
for f in folder:
# f is a sub-folder only if it starts with the last kept folder followed by "/"
if not ans or not f.startswith(ans[-1] + "/"):
ans.append(f)
return ans