VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-the-number-of-words-with-given-prefix-using-trie/

⇱ Count the number of words with given prefix using Trie - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count the number of words with given prefix using Trie

Last Updated : 12 Jul, 2025

Prerequisite:Trie

Given a list of stringstr[] and a prefix string pre. The task is to count the number of words in the list of string with a given prefix using trie.

Examples:

Input:str = [ "apk", "app", "apple", "arp", "array" ], pre = "ap" 
Output:
Explanation:
Below is the representation of trie from using above string. 

👁 Image


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" 
Output:

Approach:
To solve this problem Trie Data Structure is used and each node of this Trie contains the following three fields:  

  1. children: This field is used for mapping from a character to the next level trie node
  2. isEndOfWord: This field is used to distinguish the node as the end of the word node
  3. num: This field is used to count the number of times a node is visited during insertion in trie

Steps:

  • Insert a 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.
  • The value of the 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:  


Output
3

Time Complexity: O(n*l) where n = the number of words inserted in Trie and l = the length of the longest word inserted in Trie.

Auxiliary Space: O(n*l).

Comment