876295. Count words in a Trie
Medium
Count Words in a Trie
Summary
Given a Trie, count the frequency of each word stored in the Trie. The words are considered case-insensitive and should be counted together.
This problem involves working with an Advanced Data Structure (Trie) and Strings.
Detailed Explanation
To solve this problem, we need to traverse the Trie and for each node that represents a complete word, increment its frequency count. We start by initializing an empty map to store the frequency of each word.
Here's a step-by-step breakdown of the solution:
- Initialize an empty map
wordFrequencyto store the frequency of each word. - Traverse the Trie in an in-order manner (i.e., visit all nodes at the current level before moving on to the next level).
- For each node that represents a complete word, increment its frequency count in the
wordFrequencymap. Since we are considering case-insensitive words, convert both the node's value and the map key to lowercase. - After traversing the Trie, return the
wordFrequencymap.
Here is an ASCII art diagram of the Trie for better understanding:
*
/ \
* *
/ \ / \
a b c d
/
e f
/
o p
Time Complexity: O(T), where T is the number of nodes in the Trie. Space Complexity: O(1) since we only use a constant amount of space to store the wordFrequency map.
Optimized Solutions
Java
import java.util.HashMap;
import java.util.Map;
public class CountWordsInTrie {
public Map<String, Integer> countWords(TrieNode root) {
Map<String, Integer> wordFrequency = new HashMap<>();
traverse(root, "", wordFrequency);
return wordFrequency;
}
private void traverse(TrieNode node, String word, Map<String, Integer> wordFrequency) {
if (node == null) {
return;
}
word += node.value.toLowerCase();
if (node.children.isEmpty()) {
wordFrequency.put(word, wordFrequency.getOrDefault(word, 0) + 1);
} else {
for (TrieNode child : node.children) {
traverse(child, word, wordFrequency);
}
}
}
}