[InterviewBit] Shortest Unique Prefix

Shortest Unique Prefix

  • Time :
  • Space :
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
struct Trie {
unordered_map<char, Trie*> next;
int count;
Trie():count(0) {}
void insert(string& s, int p = 0) {
count += 1;
if(s.length() != p) {
if(!next.count(s[p])) next[s[p]] = new Trie();
next[s[p]]->insert(s,p+1);
}
}
};
string query(string s, Trie* t) {
Trie* runner = t;
int p = 0;
string res = "";
while(runner->count > 1) {
runner = runner->next[s[p]];
res.push_back(s[p++]);
}
return res;
}
vector<string> Solution::prefix(vector<string> &A) {
Trie* t = new Trie();
for(auto a : A) t->insert(a);
vector<string> res;
for(auto a : A) res.push_back(query(a,t));
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/06/PS/interviewbit/shortest-unique-prefix/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.