LeetCode 1804: Implement Trie II (Prefix Tree) Solution
Master LeetCode problem 1804 (Implement Trie II (Prefix Tree)), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1804. Implement Trie II (Prefix Tree)
Problem Explanation
Explanation
A trie (pronounced "try") or prefix tree is a tree data structure that is used to store a dynamic set of strings. In this problem, we are required to implement a Trie II class that supports the following operations:
insert(word: str): Inserts a word into the trie.countWordsEqualTo(word: str): Returns the number of words in the trie that are equal to the given word.countWordsStartingWith(prefix: str): Returns the number of words in the trie that have the given prefix.
To implement this, we can use a TrieNode class to represent each node in the trie. Each node will have a map of character to the next TrieNode, a count of words that end at that node, and a count of words that start with the prefix leading to that node.
Solution Code
class TrieNode {
Map<Character, TrieNode> children;
int countEndsHere;
int countStartsWith;
public TrieNode() {
children = new HashMap<>();
countEndsHere = 0;
countStartsWith = 0;
}
}
class Trie {
TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
TrieNode curr = root;
for (char c : word.toCharArray()) {
curr.countStartsWith++;
curr.children.putIfAbsent(c, new TrieNode());
curr = curr.children.get(c);
}
curr.countEndsHere++;
}
public int countWordsEqualTo(String word) {
TrieNode curr = root;
for (char c : word.toCharArray()) {
if (!curr.children.containsKey(c)) {
return 0;
}
curr = curr.children.get(c);
}
return curr.countEndsHere;
}
public int countWordsStartingWith(String prefix) {
TrieNode curr = root;
for (char c : prefix.toCharArray()) {
if (!curr.children.containsKey(c)) {
return 0;
}
curr = curr.children.get(c);
}
return curr.countStartsWith;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1804 (Implement Trie II (Prefix Tree))?
This page provides optimized solutions for LeetCode problem 1804 (Implement Trie II (Prefix Tree)) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1804 (Implement Trie II (Prefix Tree))?
The time complexity for LeetCode 1804 (Implement Trie II (Prefix Tree)) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1804 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1804 in Java, C++, or Python.