1233. Remove Sub-Folders from the Filesystem
Medium ↗ Open on LeetCode Source: Misc
Quick review
- Pattern
- Tries
- Time
- O(NlogN)
- Space
- O(N)
Standard Solution (C++)
SummaryGiven a list of absolute filesystem folder paths, return only the top-level (non-sub) folders — i.e., discard any path that is a descendant of another path in the list.
Approach
- Sort lexicographically: Sorting ensures that a parent folder always appears before its sub-folders (e.g.,
/aprecedes/a/b). - Prefix check with trailing slash: To avoid false positives (e.g.,
/abmatching/a), append/to the last accepted folder before testing whether the current path starts with it. - Greedy scan: Iterate once; if the current path does NOT start with
lastAccepted + "/", it is a new root and gets added to the result. - This runs in O(N log N) time dominated by sorting, with a single O(N) pass for the prefix checks.
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<string> removeSubfolders(vector<string>& folder) {
// Lexicographic sort guarantees a parent always precedes its children.
sort(folder.begin(), folder.end());
vector<string> result;
for (const string& path : folder) {
// Check whether 'path' is a sub-folder of the last accepted root.
// Appending '/' prevents "/ab" from being treated as a child of "/a".
if (result.empty() || path.compare(0, result.back().size() + 1,
result.back() + '/') != 0) {
result.push_back(path);
}
}
return result;
}
};
Time O(N log N) — sorting dominates; the subsequent linear scan adds O(N · L) where L is average path length Space O(N) — for the output result vector (sorting may use O(log N) stack space)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<string> removeSubfolders(vector<string>& folder) {
sort(folder.begin(), folder.end());
vector<string> res;
res.push_back(folder[0]);
for(int i=1; i<folder.size(); ++i){
string s=folder[i];
string lastFolder=res.back();
lastFolder.push_back('/');
if(s.compare(0, lastFolder.size(), lastFolder)!=0){
res.push_back(s);
}
}
return res;
}
};
// Time Complexity: O(NlogN) for sorting the input vector, where N is the number of folders. The rest of the operations are O(N) for iterating through the sorted list.
// Space Complexity: O(N) for storing the result vector Time O(NlogN) Space O(N)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.