Count the number of words with given prefix using Trie
Input: str = [ “apk”, “app”, “apple”, “arp”, “array” ], pre = “ap”
Below is the representation of trie from using above string.
The words in str having prefix “ap” are apk, app and apple.
So, the count is 3
Input: str = [ “gee”, “geek”, “geezer”, “geeksforgeeks”, “geekiness”, “geekgod” ], pre = “geek”
- children: This field is used for mapping from a character to the next level trie node
- isEndOfWord: This field is used to distinguish the node as end of word node
- num: This field is used to count the number of times a node is visited during insertion in trie
- Insert list of string in trie such that every string in the list is inserted as an individual trie node.
- During inserting update all the fields in every node of the trie
- For a given prefix, traverse the trie till we reach the last character of the given prefix pre.
- Value of num field in the last node of string pre is the count of prefix in the given list of string.
Below is the implementation of the above approach:
Time Complexity: O(n*l) where n = number of words inserted in Trie and l = length of longest word inserted in Trie.