-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1233. Remove Sub-Folders from the Filesystem.cpp
127 lines (104 loc) · 2.62 KB
/
1233. Remove Sub-Folders from the Filesystem.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
// Method - 1
class Trie{
public:
bool flag=0;
string node="";
unordered_map<string,Trie*> mp;
Trie(string ch)
{
this->node=ch;
this->flag=0;
}
};
class Solution {
public:
Trie* root=new Trie("0");
void addToTrie(string& s)
{
//cout<<s<<endl;
Trie* node=root;
string str="";
for(int i=1;i<s.length();i++)
{
if(s[i]!='/')
{
//cout<<str<<endl;
str+=s[i];
continue;
}
//cout<<str<<endl;
if(node->mp.count(str)==0)
{
//cout<<str<<endl;
Trie* newNode=new Trie(str);
node->mp[str]=newNode;
}
node=node->mp[str];
if(node->flag)
return ;
str="";
}
if(str.length()==0)
{
node->flag=1;
return ;
}
if(node->mp.count(str)==0)
{
Trie* newNode=new Trie(str);
node->mp[str]=newNode;
}
node=node->mp[str];
node->flag=1;
}
void evaluate(vector<string>& ans,Trie* node,string str)
{
// base case
if(node->flag)
{
ans.push_back(str);
return ;
}
// recursive calls
for(auto& it:node->mp)
evaluate(ans,it.second,str+"/"+it.first);
}
vector<string> removeSubfolders(vector<string>& folder) {
for(auto& it:folder)
{
if(it[0]=='/')
{
//cout<<it<<endl;
addToTrie(it);
}
}
vector<string> ans;
evaluate(ans,root,"");
return ans;
}
};
// Method - 2
// Time complexity - O(NlogN)
// Space complexity- O(N)
class Solution {
public:
vector<string> removeSubfolders(vector<string>& folder) {
sort(folder.begin(),folder.end());
vector<string> ans;
ans.push_back(folder[0]);
for(int i=1;i<folder.size();i++)
{
string temp=folder[i].substr(0,ans.back().size());
int ind=ans.back().length();
while(ind<folder[i].length() and folder[i][ind]!='/')
{
temp+=folder[i][ind];
ind++;
}
temp+='/';
if((ans.back()+'/')!=temp)
ans.push_back(folder[i]);
}
return ans;
}
};