Remove Sub-Folders from the Filesystem in C++

Suppose we have a list of folders, we have to remove all sub-folders in those folders and return in any order the folders after removing. Here if a folder[i] is located within another folder[j], it is denoted as subfolder of it. The paths will be like folder1/subfolder2/… etc.

Suppose the input is like

["/myfolder","/myfolder/secondfolder","/another/document","/another/document/extrafolder","/another/final"], then the output will be:

To solve this, we will follow these steps −

  • sort the folder array based on the length of the paths
  • create one map m, and another array ans
  • for i in range 0 to size of path array – 1
    • s := path_array[i]
    • temp := empty string
    • set flag as true
    • for j in range 0 to size of s
      • temp := temp + s[j]
      • increase j by 1
      • while j < size of array and s[j] is not ‘/’
        • temp := temp + s[j], and increase j by 1
      • if m[temp] is not false, then flag := false, and break
  • if flag is true, then insert s into ans, and set m[s] := true
  • return ans

Let us see the following implementation to get better understanding −


 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   cout << "]"<<endl;
class Solution {
   static bool cmp(string s,string x){
      return s.size()<x.size();
   vector<string> removeSubfolders(vector<string>& f) {
      map <string,bool> m;
      vector <string> ans;
      for(int i =0;i<f.size();i++){
         string s= f[i];
         string temp="";
         bool flag = true;
         for(int j =0;j<s.size();){
            while(j<s.size() && s[j]!='/'){
               flag = false;
      return ans;
   vector<string> v = {"/myfolder","/myfolder/secondfolder","/another/document","/another/document/extrafolder","/another/final"};
   Solution ob;




[/myfolder, /another/final, /another/document, ]