Implement Trie Prefix Tree in Python and Java
In this tutorial, we will learn LeetCode #208: Implement Trie Prefix Tree in very simple language. We will understand the idea step by step, see custom examples, and write complete code in Python and Java.
What Is the Implement Trie Prefix Tree Problem?
This problem asks us to solve a common coding interview task using the given input. The goal is to return the correct result without using a slow brute force method.
For this problem, we will use trie because it gives a clean and optimized solution.
Example input:
operations = insert("cat"), search("cat"), startsWith("ca")
Expected result:
Output: true, true
Explanation:
Trie stores characters path by path.Beginner-Friendly Idea
The main idea is to avoid trying every possible answer blindly. Instead, we keep useful information while reading the input and use that information to make the next decision.
At each step, ask: “What do I already know, and how does the current value change my answer?”
Using our example:
operations = insert("cat"), search("cat"), startsWith("ca")
Approach:
trie
We update variables step by step until we reach:
Output: true, trueWhy Do We Use This Approach?
A direct brute force solution is usually easier to think about, but it can become slow when the input is large. The optimized approach keeps only the important state and avoids repeated work.
That is why trie is useful for this problem.
Step-by-Step Explanation
Let us dry run the algorithm using a custom example.
Step 1
Use this custom example.
operations = insert("cat"), search("cat"), startsWith("ca")
We will solve it using trie.
Step 2
Look at the first important value from the example and create the variables needed by the algorithm.
current_state = based on the first value
answer = not finished yet
Step 3
Move to the next useful value and update the state.
The algorithm compares the new value with the old state.
If the new value improves the answer, we update the answer.
Step 4
Continue this process until all useful values are processed.
After processing the example, we get:
Output: true, true
Why?
Trie stores characters path by path.Important Code Logic
The most important part is updating the algorithm state after reading each useful value. This is where the answer becomes better step by step.
Think like this: old_state = what we knew before current_value = value we are checking now new_state = updated result after using current_value For our example, the final state gives: Output: true, true
Example 1
Input:
operations = insert("cat"), search("cat"), startsWith("ca")
Output:
Output: true, true
Explanation:
Trie stores characters path by path.Example 2
Input:
operations = insert("dog"), search("dog"), startsWith("do")
Output:
true, true
Explanation:
The trie stores the path d -> o -> g.Python Code
Here is the complete Python solution for LeetCode #208.
class TrieNode:
def __init__(self):
self.children = {}
self.is_word = False
class PrefixTrie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_word = True
def search(self, word):
node = self._find_node(word)
return node is not None and node.is_word
def starts_with(self, prefix):
return self._find_node(prefix) is not None
def _find_node(self, text):
node = self.root
for char in text:
if char not in node.children:
return None
node = node.children[char]
return node
trie = PrefixTrie()
trie.insert("code")
trie.insert("coder")
print(trie.search("code")) # Output: True
print(trie.search("cod")) # Output: False
print(trie.starts_with("cod")) # Output: TrueJava Code
Here is the complete Java solution for LeetCode #208.
class TrieNode {
TrieNode[] children = new TrieNode[26];
boolean isWord;
}
class PrefixTrie {
private TrieNode root = new TrieNode();
public void insert(String word) {
TrieNode node = root;
for (char ch : word.toCharArray()) {
int index = ch - 'a';
if (node.children[index] == null) node.children[index] = new TrieNode();
node = node.children[index];
}
node.isWord = true;
}
public boolean search(String word) {
TrieNode node = findNode(word);
return node != null && node.isWord;
}
public boolean startsWith(String prefix) {
return findNode(prefix) != null;
}
private TrieNode findNode(String text) {
TrieNode node = root;
for (char ch : text.toCharArray()) {
int index = ch - 'a';
if (node.children[index] == null) return null;
node = node.children[index];
}
return node;
}
public static void main(String[] args) {
PrefixTrie trie = new PrefixTrie();
trie.insert("code");
trie.insert("coder");
System.out.println(trie.search("code")); // true
System.out.println(trie.search("cod")); // false
System.out.println(trie.startsWith("cod")); // true
}
}Time and Space Complexity
Time Complexity: O(n)
The time complexity depends on how many values the algorithm needs to process and whether it uses sorting, binary search, heap, or traversal.
Space Complexity: O(n)
The extra space is used for the variables or data structures needed by the optimized approach.
Final Summary
LeetCode #208: Implement Trie Prefix Tree becomes easier when we break it into small steps. First understand what the problem asks, then track the important state, dry run with an example, and finally write the code.