-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0208_implement_trie.html
More file actions
598 lines (504 loc) · 20.3 KB
/
0208_implement_trie.html
File metadata and controls
598 lines (504 loc) · 20.3 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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>208 - Implement Trie (Prefix Tree)</title>
<link rel="stylesheet" href="styles.css">
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<div class="container">
<div class="problem-info">
<h1><span class="problem-number">#208</span> Implement Trie (Prefix Tree)</h1>
<p>
Implement a Trie (prefix tree) with insert, search, and startsWith methods.
A Trie efficiently stores and retrieves strings for autocomplete and spell-checking.
</p>
<div class="problem-meta">
<span class="meta-tag">🌳 Tree</span>
<span class="meta-tag">🌲 Trie</span>
<span class="meta-tag">🏗️ Design</span>
<span class="meta-tag">⏱️ O(n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0208_implement_trie_(prefix_tree)/0208_implement_trie_(prefix_tree).py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>Tree traversal is like <strong>exploring a family tree</strong>:</p>
<ul>
<li><strong>Root:</strong> Start at the top node</li>
<li><strong>Recurse:</strong> Visit left and right children</li>
<li><strong>Base case:</strong> Stop at null/leaf nodes</li>
<li><strong>Combine:</strong> Build answer from subtree results</li>
</ul>
</div>
<section class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<button id="autoRunBtn" class="btn">▶ Auto Run</button>
<button id="stepBtn" class="btn btn-success">Step</button>
<button id="resetBtn" class="btn btn-danger">Reset</button>
</div>
<div class="status" id="status">Click Auto Run to simulate Trie operations</div>
<svg id="visualization"></svg>
</section>
<section class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List, Optional
"""
LeetCode 208. Implement Trie (Prefix Tree)
Problem from LeetCode: https://leetcode.com/problems/implement-trie-prefix-tree/
Description:
A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.
Implement the Trie class:
- Trie() Initializes the trie object.
- void insert(String word) Inserts the string word into the trie.
- boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.
- boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.
Example 1:
Input
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
Output
[null, null, true, false, true, null, true]
Explanation
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // return True
trie.search("app"); // return False
trie.startsWith("app"); // return True
trie.insert("app");
trie.search("app"); // return True
Constraints:
- 1 <= word.length, prefix.length <= 2000
- word and prefix consist only of lowercase English letters.
- At most 3 * 10^4 calls in total will be made to insert, search, and startsWith.
"""
class TrieNode:
"""
A node in the Trie data structure.
Each node contains links to its children and a flag indicating if it's the end of a word.
"""
def __init__(self):
"""Initialize an empty TrieNode with 26 possible children (for lowercase letters a-z)."""
self.links = [None] * 26
self.is_end = False
def contains_key(self, ch: str) ->bool:
"""
Check if the node contains a link for the given character.
Args:
ch: A single character
Returns:
bool: True if the link exists, False otherwise
"""
return self.links[ord(ch) - ord('a')] is not None
def get(self, ch: str) ->'TrieNode':
"""
Get the node linked to the given character.
Args:
ch: A single character
Returns:
TrieNode: The linked node for the character
"""
return self.links[ord(ch) - ord('a')]
def put(self, ch: str, node: 'TrieNode') ->None:
"""
Create a link to a node for the given character.
Args:
ch: A single character
node: The TrieNode to link to
"""
self.links[ord(ch) - ord('a')] = node
def set_end(self) ->None:
"""Mark the current node as the end of a word."""
self.is_end = True
def is_end_of_word(self) ->bool:
"""
Check if the current node marks the end of a word.
Returns:
bool: True if this node marks the end of a word, False otherwise
"""
return self.is_end
class Trie:
"""
Trie data structure for efficient word storage and retrieval.
Supports insertion, search, and prefix search operations.
"""
def __init__(self):
"""Initialize an empty Trie with a root node."""
self.root = TrieNode()
def insert(self, word: str) ->None:
"""
Insert a word into the trie.
Args:
word: The word to insert
"""
node = self.root
for ch in word:
if not node.contains_key(ch):
node.put(ch, TrieNode())
node = node.get(ch)
node.set_end()
def search_prefix(self, word: str) ->TrieNode:
"""
Search for a prefix in the trie.
Args:
word: The prefix to search for
Returns:
TrieNode: The node at the end of the prefix path, or None if prefix not found
"""
node = self.root
for ch in word:
if node.contains_key(ch):
node = node.get(ch)
else:
return None
return node
def search(self, word: str) ->bool:
"""
Search for a complete word in the trie.
Args:
word: The word to search for
Returns:
bool: True if the word exists in the trie, False otherwise
"""
node = self.search_prefix(word)
return node is not None and node.is_end_of_word()
def starts_with(self, prefix: str) ->bool:
"""
Check if there is any word in the trie that starts with the given prefix.
Args:
prefix: The prefix to search for
Returns:
bool: True if at least one word with the prefix exists, False otherwise
"""
node = self.search_prefix(prefix)
return node is not None
if __name__ == '__main__':
# Example usage based on LeetCode sample
print("Example 1:")
print("Operations: [\"Trie\", \"insert\", \"search\", \"search\", \"startsWith\", \"insert\", \"search\"]")
print("Values: [[], [\"apple\"], [\"apple\"], [\"app\"], [\"app\"], [\"app\"], [\"app\"]]")
print("Output:")
trie = Trie() # null
print("Trie() -> null")
trie.insert("apple") # null
print("insert(\"apple\") -> null")
result1 = trie.search("apple")
print(f"search(\"apple\") -> {result1}") # return True
result2 = trie.search("app")
print(f"search(\"app\") -> {result2}") # return False
result3 = trie.starts_with("app")
print(f"startsWith(\"app\") -> {result3}") # return True
trie.insert("app") # null
print("insert(\"app\") -> null")
result4 = trie.search("app")
print(f"search(\"app\") -> {result4}") # return True
</pre>
</div>
</section>
</div>
<script>
const width = 900;
const height = 550;
const svg = d3.select("#visualization")
.attr("width", width)
.attr("height", height);
// Operations sequence
const operations = [
{ op: "insert", arg: "apple" },
{ op: "search", arg: "apple", expected: true },
{ op: "search", arg: "app", expected: false },
{ op: "startsWith", arg: "app", expected: true },
{ op: "insert", arg: "app" },
{ op: "search", arg: "app", expected: true },
{ op: "insert", arg: "apricot" },
{ op: "startsWith", arg: "apr", expected: true }
];
let trie = { children: {}, isEnd: false };
let operationIdx = 0;
let highlightPath = [];
let lastResult = null;
let animationTimer = null;
function reset() {
trie = { children: {}, isEnd: false };
operationIdx = 0;
highlightPath = [];
lastResult = null;
if (animationTimer) clearInterval(animationTimer);
document.getElementById("status").textContent = "Click Auto Run to simulate Trie operations";
render();
}
function render() {
svg.selectAll("*").remove();
// Draw trie structure
drawTrie();
// Draw operations panel
drawOperations();
}
function drawTrie() {
const startX = 200;
const startY = 80;
svg.append("text")
.attr("x", 30)
.attr("y", 40)
.attr("font-size", "16px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Trie Structure:");
// Draw root node
svg.append("circle")
.attr("cx", startX)
.attr("cy", startY)
.attr("r", 22)
.attr("fill", "#f8fafc")
.attr("stroke", "#94a3b8")
.attr("stroke-width", 2);
svg.append("text")
.attr("x", startX)
.attr("y", startY + 5)
.attr("text-anchor", "middle")
.attr("font-size", "11px")
.attr("fill", "#64748b")
.text("root");
// Recursively draw nodes
const nodePositions = {};
drawNode(trie, startX, startY, 0, '', nodePositions);
}
function drawNode(node, x, y, level, pathKey, positions) {
const children = Object.entries(node.children);
if (children.length === 0) return;
const spacing = Math.max(50, 200 / Math.pow(1.5, level));
const childY = y + 70;
children.forEach(([char, childNode], idx) => {
const offset = (idx - (children.length - 1) / 2) * spacing;
const childX = x + offset;
const childPath = pathKey + char;
const isHighlighted = highlightPath.length > 0 &&
childPath === highlightPath.slice(0, childPath.length).join('');
// Draw edge
svg.append("line")
.attr("x1", x)
.attr("y1", y + 22)
.attr("x2", childX)
.attr("y2", childY - 18)
.attr("stroke", isHighlighted ? "#10b981" : "#cbd5e1")
.attr("stroke-width", isHighlighted ? 3 : 2);
// Draw edge label
const midX = (x + childX) / 2;
const midY = (y + 22 + childY - 18) / 2;
svg.append("circle")
.attr("cx", midX)
.attr("cy", midY)
.attr("r", 10)
.attr("fill", isHighlighted ? "#d1fae5" : "#f1f5f9");
svg.append("text")
.attr("x", midX)
.attr("y", midY + 4)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("font-weight", "bold")
.attr("fill", isHighlighted ? "#059669" : "#1e293b")
.text(char);
// Draw child node
svg.append("circle")
.attr("cx", childX)
.attr("cy", childY)
.attr("r", 18)
.attr("fill", () => {
if (childNode.isEnd && isHighlighted) return "#bbf7d0";
if (isHighlighted) return "#fef3c7";
if (childNode.isEnd) return "#dbeafe";
return "#f8fafc";
})
.attr("stroke", () => {
if (isHighlighted) return "#10b981";
if (childNode.isEnd) return "#3b82f6";
return "#94a3b8";
})
.attr("stroke-width", isHighlighted ? 3 : 2);
// Word end marker
if (childNode.isEnd) {
svg.append("circle")
.attr("cx", childX + 12)
.attr("cy", childY - 12)
.attr("r", 6)
.attr("fill", "#10b981")
.attr("stroke", "white")
.attr("stroke-width", 1);
}
// Recurse
drawNode(childNode, childX, childY, level + 1, childPath, positions);
});
}
function drawOperations() {
const x = 520;
const y = 60;
svg.append("text")
.attr("x", x)
.attr("y", y - 10)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Operations:");
operations.forEach((op, idx) => {
const isComplete = idx < operationIdx;
const isCurrent = idx === operationIdx;
const opY = y + idx * 32;
let text;
if (op.op === "insert") {
text = `insert("${op.arg}")`;
} else if (op.op === "search") {
const result = isComplete && idx === operationIdx - 1 ? lastResult : (isComplete ? op.expected : "?");
text = `search("${op.arg}") → ${result}`;
} else {
const result = isComplete && idx === operationIdx - 1 ? lastResult : (isComplete ? op.expected : "?");
text = `startsWith("${op.arg}") → ${result}`;
}
svg.append("rect")
.attr("x", x)
.attr("y", opY)
.attr("width", 220)
.attr("height", 26)
.attr("rx", 4)
.attr("fill", () => {
if (isCurrent) return "#fef3c7";
if (isComplete) return "#d1fae5";
return "#f8fafc";
})
.attr("stroke", () => {
if (isCurrent) return "#f59e0b";
if (isComplete) return "#10b981";
return "#e2e8f0";
});
svg.append("text")
.attr("x", x + 10)
.attr("y", opY + 18)
.attr("font-size", "12px")
.attr("fill", "#1e293b")
.text(text);
});
// Legend
const legendY = 340;
svg.append("text")
.attr("x", x)
.attr("y", legendY)
.attr("font-size", "12px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Legend:");
// End of word marker
svg.append("circle")
.attr("cx", x + 10)
.attr("cy", legendY + 20)
.attr("r", 6)
.attr("fill", "#10b981");
svg.append("text")
.attr("x", x + 25)
.attr("y", legendY + 25)
.attr("font-size", "11px")
.attr("fill", "#64748b")
.text("End of word marker");
// Time complexity
svg.append("text")
.attr("x", 30)
.attr("y", 430)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text("Time Complexity: O(m) for all operations, where m is word/prefix length");
svg.append("text")
.attr("x", 30)
.attr("y", 450)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text("Space Complexity: O(m * n) where n is number of words");
}
function insert(word) {
let node = trie;
highlightPath = [];
for (const ch of word) {
if (!node.children[ch]) {
node.children[ch] = { children: {}, isEnd: false };
}
node = node.children[ch];
highlightPath.push(ch);
}
node.isEnd = true;
}
function search(word) {
let node = trie;
highlightPath = [];
for (const ch of word) {
if (!node.children[ch]) {
return false;
}
node = node.children[ch];
highlightPath.push(ch);
}
return node.isEnd;
}
function startsWith(prefix) {
let node = trie;
highlightPath = [];
for (const ch of prefix) {
if (!node.children[ch]) {
return false;
}
node = node.children[ch];
highlightPath.push(ch);
}
return true;
}
function step() {
if (operationIdx >= operations.length) {
document.getElementById("status").textContent = "✓ All operations complete!";
return;
}
const op = operations[operationIdx];
highlightPath = [];
if (op.op === "insert") {
insert(op.arg);
lastResult = null;
document.getElementById("status").textContent =
`insert("${op.arg}") - Word added to Trie`;
} else if (op.op === "search") {
lastResult = search(op.arg);
document.getElementById("status").textContent =
`search("${op.arg}") = ${lastResult} - ${lastResult ? "Word found!" : "Word not found"}`;
} else {
lastResult = startsWith(op.arg);
document.getElementById("status").textContent =
`startsWith("${op.arg}") = ${lastResult} - ${lastResult ? "Prefix exists!" : "Prefix not found"}`;
}
operationIdx++;
render();
}
function autoRun() {
if (animationTimer) {
clearInterval(animationTimer);
animationTimer = null;
document.getElementById("autoRunBtn").textContent = "▶ Auto Run";
return;
}
document.getElementById("autoRunBtn").textContent = "⏸ Pause";
animationTimer = setInterval(() => {
if (operationIdx >= operations.length) {
clearInterval(animationTimer);
animationTimer = null;
document.getElementById("autoRunBtn").textContent = "▶ Auto Run";
return;
}
step();
}, 1200);
}
document.getElementById("autoRunBtn").addEventListener("click", autoRun);
document.getElementById("stepBtn").addEventListener("click", step);
document.getElementById("resetBtn").addEventListener("click", reset);
reset();
</script>
</body>
</html>