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.
word and prefix consist only of lowercase English letters.
At most 3 * 104 calls in total will be made to insert, search, and startsWith.
Solutions
Solution 1: Trie (Prefix Tree)
Each node in the trie contains two parts:
An array of pointers to child nodes children. For this problem, the array length is 26, representing the number of lowercase English letters. children[0] corresponds to lowercase letter 'a', ..., and children[25] corresponds to lowercase letter 'z'.
A boolean field isEnd indicating whether the node is the end of a string.
1. Insert a String
We start from the root of the trie and insert the string. For the child node corresponding to the current character, there are two cases:
The child node exists. Move along the pointer to the child node and continue processing the next character.
The child node does not exist. Create a new child node, record it in the corresponding position of the children array, then move along the pointer to the child node and continue searching for the next character.
Repeat the above steps until the last character of the string is processed, then mark the current node as the end of the string.
2. Search for a Prefix
We start from the root of the trie and search for the prefix. For the child node corresponding to the current character, there are two cases:
The child node exists. Move along the pointer to the child node and continue searching for the next character.
The child node does not exist. This means the trie does not contain the prefix, so return a null pointer.
Repeat the above steps until a null pointer is returned or the last character of the prefix is searched.
If we search to the end of the prefix, it means the trie contains the prefix. Additionally, if the isEnd of the node corresponding to the end of the prefix is true, it means the trie contains the string.
The time complexity for inserting a string is \(O(m \times |\Sigma|)\), and the time complexity for searching a prefix is \(O(m)\), where \(m\) is the length of the string and \(|\Sigma|\) is the size of the character set (26 in this problem). The space complexity is \(O(q \times m \times |\Sigma|)\), where \(q\) is the number of inserted strings.
classTrie:def__init__(self):self.children=[None]*26self.is_end=Falsedefinsert(self,word:str)->None:node=selfforcinword:idx=ord(c)-ord('a')ifnode.children[idx]isNone:node.children[idx]=Trie()node=node.children[idx]node.is_end=Truedefsearch(self,word:str)->bool:node=self._search_prefix(word)returnnodeisnotNoneandnode.is_enddefstartsWith(self,prefix:str)->bool:node=self._search_prefix(prefix)returnnodeisnotNonedef_search_prefix(self,prefix:str):node=selfforcinprefix:idx=ord(c)-ord('a')ifnode.children[idx]isNone:returnNonenode=node.children[idx]returnnode# Your Trie object will be instantiated and called as such:# obj = Trie()# obj.insert(word)# param_2 = obj.search(word)# param_3 = obj.startsWith(prefix)
classTrie{privateTrie[]children;privatebooleanisEnd;publicTrie(){children=newTrie[26];}publicvoidinsert(Stringword){Trienode=this;for(charc:word.toCharArray()){intidx=c-'a';if(node.children[idx]==null){node.children[idx]=newTrie();}node=node.children[idx];}node.isEnd=true;}publicbooleansearch(Stringword){Trienode=searchPrefix(word);returnnode!=null&&node.isEnd;}publicbooleanstartsWith(Stringprefix){Trienode=searchPrefix(prefix);returnnode!=null;}privateTriesearchPrefix(Strings){Trienode=this;for(charc:s.toCharArray()){intidx=c-'a';if(node.children[idx]==null){returnnull;}node=node.children[idx];}returnnode;}}/** * Your Trie object will be instantiated and called as such: * Trie obj = new Trie(); * obj.insert(word); * boolean param_2 = obj.search(word); * boolean param_3 = obj.startsWith(prefix); */
classTrie{private:vector<Trie*>children;boolisEnd;Trie*searchPrefix(strings){Trie*node=this;for(charc:s){intidx=c-'a';if(!node->children[idx])returnnullptr;node=node->children[idx];}returnnode;}public:Trie():children(26),isEnd(false){}voidinsert(stringword){Trie*node=this;for(charc:word){intidx=c-'a';if(!node->children[idx])node->children[idx]=newTrie();node=node->children[idx];}node->isEnd=true;}boolsearch(stringword){Trie*node=searchPrefix(word);returnnode!=nullptr&&node->isEnd;}boolstartsWith(stringprefix){Trie*node=searchPrefix(prefix);returnnode!=nullptr;}};/** * Your Trie object will be instantiated and called as such: * Trie* obj = new Trie(); * obj->insert(word); * bool param_2 = obj->search(word); * bool param_3 = obj->startsWith(prefix); */
typeTriestruct{children[26]*TrieisEndbool}funcConstructor()Trie{returnTrie{}}func(this*Trie)Insert(wordstring){node:=thisfor_,c:=rangeword{idx:=c-'a'ifnode.children[idx]==nil{node.children[idx]=&Trie{}}node=node.children[idx]}node.isEnd=true}func(this*Trie)Search(wordstring)bool{node:=this.SearchPrefix(word)returnnode!=nil&&node.isEnd}func(this*Trie)StartsWith(prefixstring)bool{node:=this.SearchPrefix(prefix)returnnode!=nil}func(this*Trie)SearchPrefix(sstring)*Trie{node:=thisfor_,c:=ranges{idx:=c-'a'ifnode.children[idx]==nil{returnnil}node=node.children[idx]}returnnode}/** * Your Trie object will be instantiated and called as such: * obj := Constructor(); * obj.Insert(word); * param_2 := obj.Search(word); * param_3 := obj.StartsWith(prefix); */
usestd::{cell::RefCell,collections::HashMap,rc::Rc};structTrieNode{pubval:Option<char>,pubflag:bool,pubchild:HashMap<char,Rc<RefCell<TrieNode>>>,}implTrieNode{fnnew()->Self{Self{val:None,flag:false,child:HashMap::new(),}}fnnew_with_val(val:char)->Self{Self{val:Some(val),flag:false,child:HashMap::new(),}}}structTrie{root:Rc<RefCell<TrieNode>>,}/// Your Trie object will be instantiated and called as such:/// let obj = Trie::new();/// obj.insert(word);/// let ret_2: bool = obj.search(word);/// let ret_3: bool = obj.starts_with(prefix);implTrie{fnnew()->Self{Self{root:Rc::new(RefCell::new(TrieNode::new())),}}fninsert(&self,word:String){letchar_vec:Vec<char>=word.chars().collect();// Get the clone of current root nodeletmutroot=Rc::clone(&self.root);forcin&char_vec{if!root.borrow().child.contains_key(c){// We need to manually create the entryroot.borrow_mut().child.insert(*c,Rc::new(RefCell::new(TrieNode::new())));}// Get the child nodeletroot_clone=Rc::clone(root.borrow().child.get(c).unwrap());root=root_clone;}{root.borrow_mut().flag=true;}}fnsearch(&self,word:String)->bool{letchar_vec:Vec<char>=word.chars().collect();// Get the clone of current root nodeletmutroot=Rc::clone(&self.root);forcin&char_vec{if!root.borrow().child.contains_key(c){returnfalse;}// Get the child nodeletroot_clone=Rc::clone(root.borrow().child.get(c).unwrap());root=root_clone;}letflag=root.borrow().flag;flag}fnstarts_with(&self,prefix:String)->bool{letchar_vec:Vec<char>=prefix.chars().collect();// Get the clone of current root nodeletmutroot=Rc::clone(&self.root);forcin&char_vec{if!root.borrow().child.contains_key(c){returnfalse;}// Get the child nodeletroot_clone=Rc::clone(root.borrow().child.get(c).unwrap());root=root_clone;}true}}
/** * Initialize your data structure here. */varTrie=function(){this.children={};};/** * Inserts a word into the trie. * @param {string} word * @return {void} */Trie.prototype.insert=function(word){letnode=this.children;for(letcharofword){if(!node[char]){node[char]={};}node=node[char];}node.isEnd=true;};/** * Returns if the word is in the trie. * @param {string} word * @return {boolean} */Trie.prototype.search=function(word){letnode=this.searchPrefix(word);returnnode!=undefined&&node.isEnd!=undefined;};Trie.prototype.searchPrefix=function(prefix){letnode=this.children;for(letcharofprefix){if(!node[char])returnfalse;node=node[char];}returnnode;};/** * Returns if there is any word in the trie that starts with the given prefix. * @param {string} prefix * @return {boolean} */Trie.prototype.startsWith=function(prefix){returnthis.searchPrefix(prefix);};/** * Your Trie object will be instantiated and called as such: * var obj = new Trie() * obj.insert(word) * var param_2 = obj.search(word) * var param_3 = obj.startsWith(prefix) */
publicclassTrie{boolisEnd;Trie[]children=newTrie[26];publicTrie(){}publicvoidInsert(stringword){Trienode=this;foreach(varcinword){varidx=c-'a';node.children[idx]??=newTrie();node=node.children[idx];}node.isEnd=true;}publicboolSearch(stringword){Trienode=SearchPrefix(word);returnnode!=null&&node.isEnd;}publicboolStartsWith(stringprefix){Trienode=SearchPrefix(prefix);returnnode!=null;}privateTrieSearchPrefix(strings){Trienode=this;foreach(varcins){varidx=c-'a';if(node.children[idx]==null){returnnull;}node=node.children[idx];}returnnode;}}/** * Your Trie object will be instantiated and called as such: * Trie obj = new Trie(); * obj.Insert(word); * bool param_2 = obj.Search(word); * bool param_3 = obj.StartsWith(prefix); */