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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer DSA Live Classes