208. Implement Trie (Prefix Tree) LeetCode Solution
In this guide, you will get 208. Implement Trie (Prefix Tree) LeetCode Solution with the best time and space complexity. The solution to Implement Trie (Prefix Tree) problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Implement Trie (Prefix Tree) solution in C++
- Implement Trie (Prefix Tree) solution in Java
- Implement Trie (Prefix Tree) solution in Python
- Additional Resources
Problem Statement of Implement Trie (Prefix Tree)
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 * 104 calls in total will be made to insert, search, and startsWith.
Complexity Analysis
- Time Complexity:
- Space Complexity:
208. Implement Trie (Prefix Tree) LeetCode Solution in C++
struct TrieNode {
vector<shared_ptr<TrieNode>> children;
bool isWord = false;
TrieNode() : children(26) {}
};
class Trie {
public:
void insert(const string& word) {
shared_ptr<TrieNode> node = root;
for (const char c : word) {
const int i = c - 'a';
if (node->children[i] == nullptr)
node->children[i] = make_shared<TrieNode>();
node = node->children[i];
}
node->isWord = true;
}
bool search(const string& word) {
shared_ptr<TrieNode> node = find(word);
return node && node->isWord;
}
bool startsWith(const string& prefix) {
return find(prefix) != nullptr;
}
private:
shared_ptr<TrieNode> root = make_shared<TrieNode>();
shared_ptr<TrieNode> find(const string& prefix) {
shared_ptr<TrieNode> node = root;
for (const char c : prefix) {
const int i = c - 'a';
if (node->children[i] == nullptr)
return nullptr;
node = node->children[i];
}
return node;
}
};
/* code provided by PROGIEZ */
208. Implement Trie (Prefix Tree) LeetCode Solution in Java
class TrieNode {
public TrieNode[] children = new TrieNode[26];
public boolean isWord = false;
}
class Trie {
public void insert(String word) {
TrieNode node = root;
for (final char c : word.toCharArray()) {
final int i = c - 'a';
if (node.children[i] == null)
node.children[i] = new TrieNode();
node = node.children[i];
}
node.isWord = true;
}
public boolean search(String word) {
TrieNode node = find(word);
return node != null && node.isWord;
}
public boolean startsWith(String prefix) {
return find(prefix) != null;
}
private TrieNode root = new TrieNode();
private TrieNode find(String prefix) {
TrieNode node = root;
for (final char c : prefix.toCharArray()) {
final int i = c - 'a';
if (node.children[i] == null)
return null;
node = node.children[i];
}
return node;
}
}
// code provided by PROGIEZ
208. Implement Trie (Prefix Tree) LeetCode Solution in Python
class TrieNode:
def __init__(self):
self.children: dict[str, TrieNode] = {}
self.isWord = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str) -> None:
node: TrieNode = self.root
for c in word:
node = node.children.setdefault(c, TrieNode())
node.isWord = True
def search(self, word: str) -> bool:
node: TrieNode = self._find(word)
return node and node.isWord
def startsWith(self, prefix: str) -> bool:
return self._find(prefix)
def _find(self, prefix: str) -> TrieNode | None:
node: TrieNode = self.root
for c in prefix:
if c not in node.children:
return None
node = node.children[c]
return node
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.