๐น Problem: 1233. Remove Sub-Folders from the Filesystem
Difficulty: #Medium
Tags: #String, #Sorting
๐ Problem Summary
Youโre given a list of folder paths (e.g., ["/a","/a/b","/c/d","/c/d/e","/c/f"]).
The task is to remove all sub-folders, keeping only the top-level parent folders.
A folder
f1is a sub-folder off2iff1starts withf2 + "/".
Return a list of folders excluding all sub-folders.
๐ง My Thought Process
Brute Force Idea:
For each folder, check if it's a subfolder of any other folder in the list. That would beO(nยฒ)comparisons. Not scalable.-
Optimized Strategy:
Sort the folders lexicographically. That way, any subfolder will immediately follow its parent.- Initialize the result list with the first folder.
- For every folder from index
1onward: - If it doesnโt start with the last added folder +
'/', it's a top-level folder โ add it to result.
Algorithm Used:
Sorting + Prefix Check
โ๏ธ Code Implementation (Python)
class Solution:
def removeSubfolders(self, folder: List[str]) -> List[str]:
folder.sort() # Lexicographically sort paths
res = [folder[0]] # First one is always a root
for f in folder[1:]:
prev = res[-1]
# Check if `f` is NOT a subfolder of the last added root
if not (f.startswith(prev) and len(f) > len(prev) and f[len(prev)] == "/"):
res.append(f)
return res
โฑ๏ธ Time & Space Complexity
-
Time:
O(n log n)โ Sorting takesn log n, rest is linear scan -
Space:
O(n)โ Result list
๐งฉ Key Takeaways
- โ Learned how lexicographic sorting simplifies hierarchical string problems.
- ๐ก Tricky part was making sure we don't falsely match
/a/bcas subfolder of/a. - ๐ญ Will look out for prefix-matching problems where sorted input helps reduce complexity.
๐ Reflection (Self-Check)
- [x] Could I solve this without help?
- [x] Did I write code from scratch?
- [x] Did I understand why it works?
- [x] Will I be able to recall this in a week?
๐ Progress Tracker
| Metric | Value |
|---|---|
| Day | 48 |
| Total Problems Solved | 389 |
| Confidence Today | ๐ |
| Leetcode Rating | 1572 |
Top comments (0)