Remove Sub-Folders from the Filesystem in C++

C++Server Side ProgrammingProgramming

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:
["/myfolder","/another/final","/another/document"]

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 −

Example

 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 {
   public:
   static bool cmp(string s,string x){
      return s.size()<x.size();
   }
   vector<string> removeSubfolders(vector<string>& f) {
      sort(f.begin(),f.end(),cmp);
      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();){
            temp+=s[j];
            j++;
            while(j<s.size() && s[j]!='/'){
               temp+=s[j];
               j++;
            }
            if(m[temp]){
               flag = false;
               break;
            }
         }
         if(flag){
            ans.push_back(s);
            m[s]=true;
         }
      }
      return ans;
   }
};
main(){
   vector<string> v = {"/myfolder","/myfolder/secondfolder","/another/document","/another/document/extrafolder","/another/final"};
   Solution ob;
   print_vector(ob.removeSubfolders(v));
}

Input

["/myfolder","/myfolder/secondfolder","/another/document","/another/document/extrafolder","/another/final"]

Output

[/myfolder, /another/final, /another/document, ]
raja
Published on 30-Apr-2020 13:08:36
Advertisements