Skip to content

Create 1233. Remove Sub-Folders from the Filesystem1 #844

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 19, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions 1233. Remove Sub-Folders from the Filesystem1
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
class Solution {
public:
vector<string> removeSubfolders(vector<string>& folder) {
// Sort all folders lexicographically
// This ensures parent folders come before their subfolders
sort(folder.begin(), folder.end());

vector<string> result;

// Add the first folder - it can't be a subfolder of anything
result.push_back(folder[0]);

// Check each folder starting from the second one
for(int i = 1; i < folder.size(); i++) {
// Get the last folder we added to result
string lastFolder = result.back();

// Add "/" to ensure we're checking for actual subfolders
// This prevents "/a" from being considered a parent of "/ab"
lastFolder += "/";

// Check if current folder starts with the last added folder
// If it doesn't start with lastFolder, it's not a subfolder
if(folder[i].substr(0, lastFolder.length()) != lastFolder) {
result.push_back(folder[i]);
}
// If it does start with lastFolder, it's a subfolder, so skip it
}

return result;
}
};
Loading