208. Implement Trie (Prefix Tree)
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to implement a Trie, also known as a prefix tree. A Trie is a special tree-based data structure used for storing and retrieving strings efficiently. It's particularly useful for tasks involving prefixes, like autocomplete and spell checking. We need to implement three main functionalities:
Solution
Implement Trie (Prefix Tree) in Python
class Trie:
def __init__(self):
"""
Initialize your data structure here.
We use a dictionary to represent the Trie. Each key is a character,
and the value is another dictionary (a sub-trie).
A special marker, e.g., 'is_end', indicates the end of a word.
"""
self.root = {}
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
node = self.root
for char in word:
# setdefault is a convenient way to get a key's value or insert it if not present
node = node.setdefault(char, {})
node['is_end'] = True
def _search_prefix(self, prefix: str) -> dict:
"""
Helper method to search for a prefix.
Returns the node corresponding to the end of the prefix, or None if not found.
"""
node = self.root
for char in prefix:
if char not in node:
return None
node = node[char]
return node
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
A word exists if its path exists and the final node is marked as an end of a word.
"""
node = self._search_prefix(word)
return node is not None and 'is_end' in node
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
A prefix exists if its path exists in the trie.
"""
return self._search_prefix(prefix) is not None
# 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)
Implement Trie (Prefix Tree) in Java
class Trie {
// TrieNode structure
private class TrieNode {
TrieNode[] children;
boolean isEndOfWord;
public TrieNode() {
children = new TrieNode[26];
isEndOfWord = false;
}
}
private final TrieNode root;
/** Initialize your data structure here. */
public Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
int index = c - 'a';
if (node.children[index] == null) {
node.children[index] = new TrieNode();
}
node = node.children[index];
}
node.isEndOfWord = true;
}
// Helper function to search for a prefix and return the last node.
private TrieNode searchPrefix(String prefix) {
TrieNode node = root;
for (char c : prefix.toCharArray()) {
int index = c - 'a';
if (node.children[index] == null) {
return null;
}
node = node.children[index];
}
return node;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode node = searchPrefix(word);
return node != null && node.isEndOfWord;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode node = searchPrefix(prefix);
return node != null;
}
}
/**
* 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);
*/
Implement Trie (Prefix Tree) in C++
class Trie {
private:
// TrieNode structure
struct TrieNode {
TrieNode* children[26];
bool isEndOfWord;
TrieNode() {
isEndOfWord = false;
for (int i = 0; i < 26; ++i) {
children[i] = nullptr;
}
}
};
TrieNode* root;
// Helper function to search for a prefix and return the last node.
TrieNode* searchPrefix(string prefix) {
TrieNode* node = root;
for (char c : prefix) {
int index = c - 'a';
if (!node->children[index]) {
return nullptr;
}
node = node->children[index];
}
return node;
}
public:
/** Initialize your data structure here. */
Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
void insert(string word) {
TrieNode* node = root;
for (char c : word) {
int index = c - 'a';
if (!node->children[index]) {
node->children[index] = new TrieNode();
}
node = node->children[index];
}
node->isEndOfWord = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
TrieNode* node = searchPrefix(word);
return node != nullptr && node->isEndOfWord;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
return searchPrefix(prefix) != 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);
*/
Implement Trie (Prefix Tree) in TypeScript
class TrieNode {
// Using an object as a dictionary to store children nodes.
// Key is the character, value is the next TrieNode.
children: { [key: string]: TrieNode } = {};
// Marks if the node is the end of a complete word.
isEndOfWord: boolean = false;
}
class Trie {
private root: TrieNode;
constructor() {
this.root = new TrieNode();
}
insert(word: string): void {
let node = this.root;
for (const char of word) {
if (!node.children[char]) {
node.children[char] = new TrieNode();
}
node = node.children[char];
}
node.isEndOfWord = true;
}
// Helper function to search for a prefix and return the last node.
private searchPrefix(prefix: string): TrieNode | null {
let node = this.root;
for (const char of prefix) {
if (!node.children[char]) {
return null;
}
node = node.children[char];
}
return node;
}
search(word: string): boolean {
const node = this.searchPrefix(word);
// The word exists if the prefix path exists and the last node is marked as an end of a word.
return node !== null && node.isEndOfWord;
}
startsWith(prefix: string): boolean {
const node = this.searchPrefix(prefix);
// The prefix exists if its path is found in the trie.
return node !== null;
}
}
/**
* 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)
*/
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.