-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtrie.cpp
More file actions
344 lines (296 loc) · 9.49 KB
/
trie.cpp
File metadata and controls
344 lines (296 loc) · 9.49 KB
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
/*
Trie (Prefix Tree) Patterns
Mathematical Foundation: Tree structure for string retrieval
Space: O(ALPHABET_SIZE * N * M) where N=words, M=avg length
Time: Insert/Search O(M), Applications: Auto-complete, spell check
*/
#include <bits/stdc++.h>
using namespace std;
// Basic Trie Implementation
// LeetCode: 208. Implement Trie (Prefix Tree)
// https://leetcode.com/problems/implement-trie-prefix-tree/
class Trie {
public:
struct TrieNode {
TrieNode* children[26];
bool isEnd;
TrieNode() {
for (int i = 0; i < 26; i++) children[i] = nullptr;
isEnd = false;
}
};
TrieNode* root;
Trie() { root = new TrieNode(); }
void insert(string word) {
TrieNode* node = root;
for (char c : word) {
int idx = c - 'a';
if (!node->children[idx]) node->children[idx] = new TrieNode();
node = node->children[idx];
}
node->isEnd = true;
}
bool search(string word) {
TrieNode* node = root;
for (char c : word) {
int idx = c - 'a';
if (!node->children[idx]) return false;
node = node->children[idx];
}
return node->isEnd;
}
bool startsWith(string prefix) {
TrieNode* node = root;
for (char c : prefix) {
int idx = c - 'a';
if (!node->children[idx]) return false;
node = node->children[idx];
}
return true;
}
};
// Add and Search Word - Data structure design
// LeetCode: 211. Design Add and Search Words Data Structure
// https://leetcode.com/problems/design-add-and-search-words-data-structure/
class WordDictionary {
struct TrieNode {
TrieNode* children[26] = {};
bool isEnd = false;
};
TrieNode* root;
public:
WordDictionary() { root = new TrieNode(); }
void addWord(string word) {
TrieNode* node = root;
for (char c : word) {
int idx = c - 'a';
if (!node->children[idx]) node->children[idx] = new TrieNode();
node = node->children[idx];
}
node->isEnd = true;
}
bool search(string word) {
function<bool(TrieNode*, int)> dfs = [&](TrieNode* node, int i) -> bool {
if (i == word.size()) return node->isEnd;
if (word[i] == '.') {
for (auto child : node->children) {
if (child && dfs(child, i + 1)) return true;
}
return false;
} else {
int idx = word[i] - 'a';
return node->children[idx] && dfs(node->children[idx], i + 1);
}
};
return dfs(root, 0);
}
};
// Word Search II (Using Trie)
// LeetCode: 212. Word Search II
// https://leetcode.com/problems/word-search-ii/
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
struct TrieNode {
TrieNode* children[26] = {};
string* word = nullptr;
};
TrieNode* root = new TrieNode();
// Build trie
for (string& w : words) {
TrieNode* node = root;
for (char c : w) {
int idx = c - 'a';
if (!node->children[idx]) node->children[idx] = new TrieNode();
node = node->children[idx];
}
node->word = &w;
}
vector<string> res;
int m = board.size(), n = board[0].size();
function<void(int, int, TrieNode*)> dfs = [&](int r, int c, TrieNode* node) {
if (r < 0 || r >= m || c < 0 || c >= n) return;
char ch = board[r][c];
if (ch == '#' || !node->children[ch - 'a']) return;
node = node->children[ch - 'a'];
if (node->word) {
res.push_back(*node->word);
node->word = nullptr; // Avoid duplicates
}
board[r][c] = '#';
dfs(r+1, c, node); dfs(r-1, c, node); dfs(r, c+1, node); dfs(r, c-1, node);
board[r][c] = ch;
};
for (int r = 0; r < m; r++) {
for (int c = 0; c < n; c++) {
dfs(r, c, root);
}
}
return res;
}
// Replace Words
// LeetCode: 648. Replace Words
// https://leetcode.com/problems/replace-words/
string replaceWords(vector<string>& dictionary, string sentence) {
struct TrieNode {
TrieNode* children[26] = {};
bool isEnd = false;
};
TrieNode* root = new TrieNode();
// Build trie
for (string& word : dictionary) {
TrieNode* node = root;
for (char c : word) {
int idx = c - 'a';
if (!node->children[idx]) node->children[idx] = new TrieNode();
node = node->children[idx];
}
node->isEnd = true;
}
auto findRoot = [&](string& word) -> string {
TrieNode* node = root;
string root_word;
for (char c : word) {
int idx = c - 'a';
if (!node->children[idx]) break;
node = node->children[idx];
root_word += c;
if (node->isEnd) return root_word;
}
return word;
};
stringstream ss(sentence);
string word, result;
bool first = true;
while (ss >> word) {
if (!first) result += " ";
result += findRoot(word);
first = false;
}
return result;
}
// Longest Word in Dictionary
// LeetCode: 720. Longest Word in Dictionary
// https://leetcode.com/problems/longest-word-in-dictionary/
string longestWord(vector<string>& words) {
struct TrieNode {
TrieNode* children[26] = {};
bool isEnd = false;
};
TrieNode* root = new TrieNode();
for (string& word : words) {
TrieNode* node = root;
for (char c : word) {
int idx = c - 'a';
if (!node->children[idx]) node->children[idx] = new TrieNode();
node = node->children[idx];
}
node->isEnd = true;
}
string result;
function<void(TrieNode*, string)> dfs = [&](TrieNode* node, string path) {
if (path.size() > result.size() ||
(path.size() == result.size() && path < result)) {
result = path;
}
for (int i = 0; i < 26; i++) {
if (node->children[i] && node->children[i]->isEnd) {
dfs(node->children[i], path + char('a' + i));
}
}
};
dfs(root, "");
return result;
}
// Concatenated Words
// LeetCode: 472. Concatenated Words
// https://leetcode.com/problems/concatenated-words/
vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
struct TrieNode {
TrieNode* children[26] = {};
bool isEnd = false;
};
TrieNode* root = new TrieNode();
for (string& word : words) {
TrieNode* node = root;
for (char c : word) {
int idx = c - 'a';
if (!node->children[idx]) node->children[idx] = new TrieNode();
node = node->children[idx];
}
node->isEnd = true;
}
auto canForm = [&](string& word) -> bool {
int n = word.size();
vector<bool> dp(n + 1);
dp[0] = true;
for (int i = 1; i <= n; i++) {
TrieNode* node = root;
for (int j = i - 1; j >= 0; j--) {
int idx = word[j] - 'a';
if (!node->children[idx]) break;
node = node->children[idx];
if (node->isEnd && dp[j] && (j > 0 || i < n)) {
dp[i] = true;
break;
}
}
}
return dp[n];
};
vector<string> result;
for (string& word : words) {
if (canForm(word)) result.push_back(word);
}
return result;
}
// Short Encoding of Words
// LeetCode: 820. Short Encoding of Words
// https://leetcode.com/problems/short-encoding-of-words/
int minimumLengthEncoding(vector<string>& words) {
struct TrieNode {
TrieNode* children[26] = {};
int depth = 0;
};
TrieNode* root = new TrieNode();
vector<TrieNode*> leaves;
for (const string& word : unordered_set<string>(words.begin(), words.end())) {
TrieNode* node = root;
for (int i = word.size() - 1; i >= 0; i--) {
int idx = word[i] - 'a';
if (!node->children[idx]) node->children[idx] = new TrieNode();
node = node->children[idx];
node->depth = root->depth - i + word.size();
}
leaves.push_back(node);
}
int ans = 0;
for (TrieNode* leaf : leaves) {
bool isLeaf = true;
for (auto child : leaf->children) {
if (child) { isLeaf = false; break; }
}
if (isLeaf) ans += leaf->depth + 1;
}
return ans;
}
// Auto-complete suggestions (Common interview question)
vector<string> autoComplete(Trie& trie, string prefix) {
vector<string> suggestions;
function<void(Trie::TrieNode*, string)> dfs = [&](Trie::TrieNode* node, string current) {
if (node->isEnd) suggestions.push_back(current);
if (suggestions.size() >= 3) return; // Limit suggestions
for (int i = 0; i < 26; i++) {
if (node->children[i]) {
dfs(node->children[i], current + char('a' + i));
}
}
};
// Navigate to prefix
Trie::TrieNode* node = trie.root;
for (char c : prefix) {
int idx = c - 'a';
if (!node->children[idx]) return suggestions;
node = node->children[idx];
}
dfs(node, prefix);
return suggestions;
}