208. Implement Trie (Prefix Tree) Leetcode Solution
Implement Trie (Prefix Tree) Leetcode Problem :
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.
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
Implement Trie (Prefix Tree) Leetcode Solution :
Constraints :
- 1 <= word.length, prefix.length <= 2000
- word and prefix consist only of lowercase English letters.
- At most 3 * 104 calls in total will be made to insert, search, and startsWith.
Intuition :
This is a classic problem of trie implementation.
Trie data structure is used to store the data dictionary and algorithms for searching the words from the dictionary and provide the list of valid words for suggestion can be constructed.
Approach :
- Implement a trieNode class.
- Create a trieNode in the trie class and assign its value to NULL
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Code :
class TrieNode { public: TrieNode *child[26]; bool isWord; TrieNode() { isWord = false; for (auto &a : child) a = nullptr; } }; class Trie { TrieNode* root; public: Trie() { root = new TrieNode(); } void insert(string s) { TrieNode *p = root; for (auto &a : s) { int i = a - 'a'; if (!p->child[i]) p->child[i] = new TrieNode(); p = p->child[i]; } p->isWord = true; } bool search(string key, bool prefix=false) { TrieNode *p = root; for (auto &a : key) { int i = a - 'a'; if (!p->child[i]) return false; p = p->child[i]; } if (prefix==false) return p->isWord; return true; } bool startsWith(string prefix) { return search(prefix, true); } };
class Trie { Node root; public Trie() { root = new Node(); } public void insert(String word) { root.insert(word, 0); } public boolean search(String word) { return root.search(word, 0); } public boolean startsWith(String prefix) { return root.startsWith(prefix, 0); } class Node { Node[] nodes; boolean isEnd; Node() { nodes = new Node[26]; } private void insert(String word, int idx) { if (idx >= word.length()) return; int i = word.charAt(idx) - 'a'; if (nodes[i] == null) { nodes[i] = new Node(); } if (idx == word.length()-1) nodes[i].isEnd = true; nodes[i].insert(word, idx+1); } private boolean search(String word, int idx) { if (idx >= word.length()) return false; Node node = nodes[word.charAt(idx) - 'a']; if (node == null) return false; if (idx == word.length() - 1 && node.isEnd) return true; return node.search(word, idx+1); } private boolean startsWith(String prefix, int idx) { if (idx >= prefix.length()) return false; Node node = nodes[prefix.charAt(idx) - 'a']; if (node == null) return false; if (idx == prefix.length() - 1) return true; return node.startsWith(prefix, idx+1); } } }
class Trie: def __init__(self): self.root={} def insert(self, word: str) -> None: cur=self.root for letter in word: if letter not in cur: cur[letter]={} cur=cur[letter] cur['*']='' def search(self, word: str) -> bool: cur=self.root for letter in word: if letter not in cur: return False cur=cur[letter] return '*' in cur def startsWith(self, prefix: str) -> bool: cur=self.root for letter in prefix: if letter not in cur: return False cur=cur[letter] return True
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment