[LeetCode] Delete Duplicate Folders in System

1948. Delete Duplicate Folders in System

Due to a bug, there are many duplicate folders in a file system. You are given a 2D array paths, where paths[i] is an array representing an absolute path to the ith folder in the file system.

  • For example, [“one”, “two”, “three”] represents the path “/one/two/three”.

Two folders (not necessarily on the same level) are identical if they contain the same non-empty set of identical subfolders and underlying subfolder structure. The folders do not need to be at the root level to be identical. If two or more folders are identical, then mark the folders as well as all their subfolders.

  • For example, folders “/a” and “/b” in the file structure below are identical. They (as well as their subfolders) should all be marked:
  • /a
  • /a/x
  • /a/x/y
  • /a/z
  • /b
  • /b/x
  • /b/x/y
  • /b/z
  • However, if the file structure also included the path “/b/w”, then the folders “/a” and “/b” would not be identical. Note that “/a/x” and “/b/x” would still be considered identical even with the added folder.

Once all the identical folders and their subfolders have been marked, the file system will delete all of them. The file system only runs the deletion once, so any folders that become identical after the initial deletion are not deleted.

Return the 2D array ans containing the paths of the remaining folders after deleting all the marked folders. The paths may be returned in any order.

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
struct Trie {
string path;
map<string, Trie*> next;
bool del;
Trie(string name = "") : path(name), del(false) {};

void insert(vector<string>& paths, int pos = 0) {
if(pos == paths.size()) return;
if(!next.count(paths[pos])) next[paths[pos]] = new Trie(paths[pos]);
next[paths[pos]]->insert(paths, pos + 1);
}

string dup(unordered_map<string, Trie*>& seen) {
string sub = "";
for(auto& [_, n] : next) {
sub += n->dup(seen);
}
if(sub.length()) {
if(seen.count(sub)) seen[sub]->del = this->del = true;
else seen[sub] = this;
}

return "(" + path + sub +")";
}

void query(vector<vector<string>>& res, vector<string>& p) {
if(del) return;
if(!p.empty()) res.push_back(p);
for(auto [sub, ntr] : next) {
p.push_back(sub);
ntr->query(res,p);
p.pop_back();
}
}
};
class Solution {
public:
vector<vector<string>> deleteDuplicateFolder(vector<vector<string>>& paths) {
vector<vector<string>> res;
Trie* tr = new Trie();
for(auto& p : paths)
tr->insert(p);
tr->dup(unordered_map<string, Trie*>() = {});
tr->query(res, vector<string>() = {});
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/15/PS/LeetCode/delete-duplicate-folders-in-system/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.