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.
- Counting the number of words in a Trie
- Longest Common Prefix using Trie
- Find shortest unique prefix for every word in a given list | Set 1 (Using Trie)
- Longest prefix matching - A Trie based solution in Java
- Sorting array of strings (or words) using Trie
- Print all possible combinations of words from Dictionary using Trie
- Check if the given Trie contains words starting from every alphabet
- Sorting array of strings (or words) using Trie | Set-2 (Handling Duplicates)
- Count the number of words having sum of ASCII values less than and greater than k
- Count inversions in an array | Set 4 ( Using Trie )
- Count of distinct substrings of a string using Suffix Trie
- Count of strings whose prefix match with the given string to a given length k
- Count of words that are present in all the given sentences
- Check if the given string of words can be formed from words present in the dictionary
- Boggle | Set 2 (Using Trie)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.