[AlgoExpert] Suffix Trie Construction

Suffix Trie Construction

  • Time : O(n^2) populateSuffixTrieFrom | O(n) contains
  • Space : O(^2)
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
#include <unordered_map>
using namespace std;

// Do not edit the class below except for the
// populateSuffixTrieFrom and contains methods.
// Feel free to add new properties and methods
// to the class.
class TrieNode {
public:
unordered_map<char, TrieNode *> children;
};

class SuffixTrie {
void insert(string& s, int p) {
auto *node = root;
while(p < s.length()) {
if(!node->children.count(s[p]))
node->children[s[p]] = new TrieNode();
node = node->children[s[p++]];
}
if(!node->children.count(endSymbol))
node->children[endSymbol] = nullptr;
}
public:
TrieNode *root;
char endSymbol;

SuffixTrie(string str) {
this->root = new TrieNode();
this->endSymbol = '*';
this->populateSuffixTrieFrom(str);
}

void populateSuffixTrieFrom(string str) {
for(int i = 0; i < str.length(); i++) {
insert(str, i);
cout<<root->children.size()<<endl;
}
}

bool contains(string str) {
auto *node = root;
for(int i = 0; i < str.length(); i++) {
if(!node->children.count(str[i])) return false;
node = node->children[str[i]];
}
return node->children.count(endSymbol);
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/09/PS/AlgoExpert/suffix-trie/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.