Trie Prefix Search Autocomplete
Implement a trie for prefix search and autocomplete with insert search and remove operations.
Code
class TrieNode{children:Map<string,TrieNode>=new Map();isEnd=false;}export class Trie{private root=new TrieNode();insert(word:string):void{let node=this.root;for(const ch of word){if(!node.children.has(ch))node.children.set(ch,new TrieNode());node=node.children.get(ch)!;}node.isEnd=true;}search(word:string):boolean{let node=this.root;for(const ch of word){node=node.children.get(ch);if(!node)return false;}return node.isEnd;}startsWith(prefix:string):string[]{const result:string[]=[];let node=this.root;for(const ch of prefix){node=node.children.get(ch);if(!node)return[];}this.dfs(node,prefix,result);return result;}private dfs(node:TrieNode,prefix:string,result:string[]){if(node.isEnd)result.push(prefix);for(const[ch,child]of node.children)this.dfs(child,prefix+ch,result);}}What the code does
Count the classes TrieNode and Trie as the entire surface area of Trie Prefix Search Autocomplete.
Watch out for
- The guard
!nodeshort-circuits the flow with an earlyreturnwhen its condition holds.
Using it
The surface worth importing is Trie; the helpers around it are private to the snippet.
Interactive Tools for This Topic
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does it depend on any third-party library?
- No third-party library is referenced; the standard library covers it.
Report a problem with this exampleOpens a pre-filled issue on GitHub.