Trie for String Matching
Trie-based string matching algorithm. Optimized for multiple pattern searches. Used in autocomplete, spell checking, IP routing.
Visualization
Interactive visualization for Trie for String Matching
Interactive visualization with step-by-step execution
Implementation
1class TrieNode {
2 children = new Map<string, TrieNode>();
3 isEndOfWord = false;
4}
5
6class Trie {
7 private root = new TrieNode();
8
9 insert(word: string): void {
10 let node = this.root;
11 for (const char of word) {
12 if (!node.children.has(char)) {
13 node.children.set(char, new TrieNode());
14 }
15 node = node.children.get(char)!;
16 }
17 node.isEndOfWord = true;
18 }
19
20 search(word: string): boolean {
21 let node = this.root;
22 for (const char of word) {
23 if (!node.children.has(char)) return false;
24 node = node.children.get(char)!;
25 }
26 return node.isEndOfWord;
27 }
28
29 startsWith(prefix: string): boolean {
30 let node = this.root;
31 for (const char of prefix) {
32 if (!node.children.has(char)) return false;
33 node = node.children.get(char)!;
34 }
35 return true;
36 }
37}Deep Dive
Theoretical Foundation
Each node represents a character. Root to leaf path forms a word. Common prefixes share paths. Space: O(ALPHABET_SIZE × N × M). Fast prefix matching: O(m).
Complexity
Time
O(m)
O(m)
O(m)
Space
O(ALPHABET × N × M)
Applications
Use Cases
Related Algorithms
Knuth-Morris-Pratt (KMP) Algorithm
An efficient string pattern matching algorithm that searches for occurrences of a 'word' within a 'text' by employing the observation that when a mismatch occurs, the word itself embodies sufficient information to determine where the next match could begin. Developed by Donald Knuth, Vaughan Pratt, and James H. Morris in 1977, it's one of the most important string algorithms with O(n+m) time complexity.
Rabin-Karp Algorithm
A string-searching algorithm that uses hashing to find pattern(s) in a text. Developed by Michael O. Rabin and Richard M. Karp in 1987, it's particularly useful for multiple pattern search and plagiarism detection. Uses rolling hash for efficiency.
Boyer-Moore Algorithm
One of the most efficient string searching algorithms in practice, using two heuristics: bad character rule and good suffix rule. Developed by Robert S. Boyer and J Strother Moore in 1977, it's the standard benchmark for practical string search, often outperforming other algorithms by skipping sections of text.
Aho-Corasick Algorithm
A string-searching algorithm for locating elements of a finite set of strings (dictionary) within an input text. Invented by Alfred V. Aho and Margaret J. Corasick in 1975, it's a kind of dictionary-matching algorithm that simultaneously searches for all patterns in linear time, making it extremely efficient for multiple pattern matching.