The Wayback Machine - https://web.archive.org/web/20240901061328/https://www.geeksforgeeks.org/counting-number-words-trie/
Open In App

Counting the number of words in a Trie

Last Updated : 14 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A Trie is used to store dictionary words so that they can be searched efficiently and prefix search can be done. The task is to write a function to count the number of words. Example :

Input :     root
          /   \    \
         t   a     b
         |   |     |
         h   n     y
         |   |  \  |
         e   s  y  e
         /  |   |
         i  r   w
         |  |   |
         r  e   e
                |
                r
Output : 8
Explanation : Words formed in the Trie : 
"the", "a", "there", "answer", "any", "by", 
"bye", "their".

In Trie structure, we have a field to store end of word marker, we call it isLeaf in below implementation. To count words, we need to simply traverse the Trie and count all nodes where isLeaf is set. 

Implementation:

C++




// C++ implementation to count words in a trie
#include <bits/stdc++.h>
using namespace std;
  
#define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0])
  
// Alphabet size (# of symbols)
#define ALPHABET_SIZE (26)
  
// Converts key current character into index
// use only 'a' through 'z' and lower case
#define CHAR_TO_INDEX(c) ((int)c - (int)'a')
 
// Trie node
struct TrieNode
{
    struct TrieNode *children[ALPHABET_SIZE];
  
    // isLeaf is true if the node represents
    // end of a word
    bool isLeaf;
};
  
// Returns new trie node (initialized to NULLs)
struct TrieNode *getNode(void)
{
    struct TrieNode *pNode = new TrieNode;
        pNode->isLeaf = false;
  
    for (int i = 0; i < ALPHABET_SIZE; i++)
        pNode->children[i] = NULL;   
  
    return pNode;
}
  
// If not present, inserts key into trie
// If the key is prefix of trie node, just
// marks leaf node
void insert(struct TrieNode *root, const char *key)
{
    int length = strlen(key);
 
    struct TrieNode *pCrawl = root;
  
    for (int level = 0; level < length; level++)
    {
        int index = CHAR_TO_INDEX(key[level]);
        if (!pCrawl->children[index])
            pCrawl->children[index] = getNode();
  
        pCrawl = pCrawl->children[index];
    }
  
    // mark last node as leaf
    pCrawl->isLeaf = true;
}
 
// Function to count number of words
int wordCount(struct TrieNode *root)
{
    int result = 0;
 
    // Leaf denotes end of a word
    if (root -> isLeaf)
        result++;
     
    for (int i = 0; i < ALPHABET_SIZE; i++)   
      if (root -> children[i])
         result += wordCount(root -> children[i]);
    
    return result;  
}
 
// Driver
int main()
{
    // Input keys (use only 'a' through 'z'
    // and lower case)
    char keys[][8] = {"the", "a", "there", "answer",
                     "any", "by", "bye", "their"};
 
  
    struct TrieNode *root = getNode();
  
    // Construct Trie
    for (int i = 0; i < ARRAY_SIZE(keys); i++)
        insert(root, keys[i]);
 
    cout << wordCount(root);
     
    return 0;
}


Java




// Java implementation to count words in a trie
public class Words_in_trie {
     
    // Alphabet size (# of symbols)
    static final int ALPHABET_SIZE = 26;
      
    // Trie node
    static class TrieNode
    {
        TrieNode[] children =  new TrieNode[ALPHABET_SIZE];
        // isLeaf is true if the node represents
        // end of a word
        boolean isLeaf;
         
        TrieNode(){
            isLeaf = false;
            for (int i = 0; i < ALPHABET_SIZE; i++)
                 children[i] = null;
        }
    };
    static TrieNode root;
       
    // If not present, inserts key into trie
    // If the key is prefix of trie node, just
    // marks leaf node
    static void insert(String key)
    {
        int length = key.length();
      
        TrieNode pCrawl = root;
       
        for (int level = 0; level < length; level++)
        {
            int index = key.charAt(level) - 'a';
            if (pCrawl.children[index] == null)
                pCrawl.children[index] = new TrieNode();
       
            pCrawl = pCrawl.children[index];
        }
       
        // mark last node as leaf
        pCrawl.isLeaf = true;
    }
      
    // Function to count number of words
    static int wordCount(TrieNode root)
    {
        int result = 0;
      
        // Leaf denotes end of a word
        if (root.isLeaf)
            result++;
          
        for (int i = 0; i < ALPHABET_SIZE; i++)   
          if (root.children[i] != null )
             result += wordCount(root.children[i]);
         
        return result;  
    }
      
    // Driver Program
    public static void main(String args[])
    {
        // Input keys (use only 'a' through 'z'
        // and lower case)
        String keys[] = {"the", "a", "there", "answer",
                        "any", "by", "bye", "their"};
 
        root = new TrieNode();     
         
        // Construct Trie
        for (int i = 0; i < keys.length; i++)
            insert(keys[i]);
      
        System.out.println(wordCount(root));
    }
}
// This code is contributed by Sumit Ghosh


Python3





C#





Javascript




<script>
 
// JavaScript implementation to count words in a trie
     
// Alphabet size (# of symbols)
const ALPHABET_SIZE = 26;
 
// Trie node
class TrieNode
{
         
    constructor(){
        // isLeaf is true if the node represents
        // end of a word
        this.isLeaf = false;
        this.children = new Array(ALPHABET_SIZE).fill(null);
    }
}
 
let root = new TrieNode();
         
    // If not present, inserts key into trie
    // If the key is prefix of trie node, just
    // marks leaf node
function insert(key)
{
    let length = key.length;
     
    let pCrawl = root;
     
    for (let level = 0; level < length; level++)
    {
        let index = key.charCodeAt(level) - 'a'.charCodeAt(0);
        if (pCrawl.children[index] == null)
            pCrawl.children[index] = new TrieNode();
         
        pCrawl = pCrawl.children[index];
    }
         
    // mark last node as leaf
    pCrawl.isLeaf = true;
}
     
// Function to count number of words
function wordCount(root)
{
    let result = 0;
     
    // Leaf denotes end of a word
    if (root.isLeaf)
        result++;
         
    for (let i = 0; i < ALPHABET_SIZE; i++)   
        if (root.children[i] != null )
            result += wordCount(root.children[i]);
         
    return result;
}
     
// Driver Program
 
// Input keys (use only 'a' through 'z'
// and lower case)
let keys = ["the", "a", "there", "answer", "any", "by", "bye", "their"];
 
root = new TrieNode();   
 
// Construct Trie
for (let i = 0; i < keys.length; i++)
    insert(keys[i]);
     
document.write(wordCount(root),"</br>");
 
// This code is contributed by shinjanpatra
 
</script>


Output

8

Time complexity: O(n*k), where n is the number of words in the trie and k is the length of the longest word in the trie.

Auxiliary Space: O(n*k)



Similar Reads

Sorting array of strings (or words) using Trie | Set-2 (Handling Duplicates)
Given an array of strings, print them in alphabetical (dictionary) order. If there are duplicates in input array, we need to print all the occurrences.Examples: Input : arr[] = { "abc", "xyz", "abcd", "bcd", "abc" } Output : abc abc abcd bcd xyz Input : arr[] = { "geeks", "for", "geeks", "a", "portal", "to", "learn" } Output : a for geeks geeks lea
9 min read
Check if the given Trie contains words starting from every alphabet
Given a Trie, the task is to check if it contains words starting from every alphabet from [a - z]. Examples: Input: keys[] = {"element", "fog", "great", "hi", "ok", "ios", "parrot", "quiz", "kim", "mango", "nature", "apple", "ball", "cat", "dog", "lime", "ruby", "shine", "tinkter", "ultra", "volly", "wow", "xerox", "yak", "zenon", "joke"} Output: Y
8 min read
Sorting array of strings (or words) using Trie
Given an array of strings, print them in alphabetical (dictionary) order. If there are duplicates in input array, we need to print them only once. Examples: Input : "abc", "xy", "bcd" Output : abc bcd xy Input : "geeks", "for", "geeks", "a", "portal", "to", "learn", "can", "be", "computer", "science", "zoom", "yup", "fire", "in", "data" Output : a
8 min read
Find all words from String present after given N words
Given a string S and a list lis[] of N number of words, the task is to find every possible (N+1)th word from string S such that the 'second' word comes immediately after the 'first' word, the 'third' word comes immediately after the 'second' word, the 'fourth' word comes immediately after the 'third' word and so on. Examples: Input: S = “Siddhesh i
11 min read
Count words that appear exactly two times in an array of words
Given an array of n words. Some words are repeated twice, we need to count such words. Examples: Input : s[] = {"hate", "love", "peace", "love", "peace", "hate", "love", "peace", "love", "peace"}; Output : 1 There is only one word "hate" that appears twice Input : s[] = {"Om", "Om", "Shankar", "Tripathi", "Tom", "Jerry", "Jerry"}; Output : 2 There
6 min read
Persistent Trie | Set 1 (Introduction)
Prerequisite: TriePersistency in Data Structure Trie is one handy data structure that often comes into play when performing multiple string lookups. In this post, we will introduce the concept of Persistency in this data structure. Persistency simply means to retain the changes. But obviously, retaining the changes cause extra memory consumption an
15+ min read
Bottom-up traversal of a Trie
Trie is an efficient information retrieval data structure. Using Trie, search complexities can be brought to an optimal limit (key length). Given a trie. The task is to print the characters in a bottom-up manner Bottom-up traversal: First print string of left most subtree(from bottom to top) then print string of second left subtree(from bottom to t
10 min read
Implement a Dictionary using Trie
Implement a dictionary using Trie such that if the input is a string representing a word, the program prints its meaning from the prebuilt dictionary. Examples: Input: str = "map" Output: a diagrammatic representation of an area Input: str = "language" Output: the method of human communication Approach: We can use a Trie to efficiently store string
9 min read
Insertion in a Trie recursively
Trie is an efficient information retrieval data structure. Using Trie, search complexities can be brought to an optimal limit (key length). Given multiple strings. The task is to insert the string in a Trie using recursion.Examples: Input : str = {"cat", "there", "caller", "their", "calling"} Output : caller calling cat there their root / \ c t | |
12 min read
Search in a trie Recursively
Trie is an efficient information retrieval data structure. Using Trie, search complexities can be brought to an optimal limit (key length).The task is to search a string in a Trie using recursion.Examples : root / \ t a | | h n | | \ e s y / | | i r w | | | r e e | r Input : str = "anywhere" Output : not found Input : str = "answer" Output : found
11 min read
Trie Data Structure using smart pointer and OOP in C++
We will implement trie using smart pointers in C++ and OOP. Here, We have already discussed the implementation of trie data using recursionIn our implementation node of a trie look like : C/C++ Code class TrieNode{ public: // Use of shared_ptr for storing Children // Pointers of TrieNode shared_ptr children[ALPHABET_SIZE]; // Tracks whether If this
6 min read
Count inversions in an array | Set 4 ( Using Trie )
Inversion Count for an array indicates – how far (or close) the array is from being sorted. If the array is already sorted then inversion count is 0. If the array is sorted in reverse order that inversion count is the maximum. Two elements a[i] and a[j] form an inversion if a[i] &gt; a[j] and i &lt; j. For simplicity, we may assume that all element
12 min read
Print Strings In Reverse Dictionary Order Using Trie
Trie is an efficient information retrieval data structure. Using Trie, search complexities can be brought to an optimal limit. Given an array of strings. The task is to print all strings in reverse dictionary order using Trie. If there are duplicates in the input array, we need to print them only once. Examples: Input: str = {"cat", "there", "calle
12 min read
Print all possible joints of a Trie constructed from a given list of strings
Given a set of strings str, the task is to print all the joints of the Trie constructed from the given set of strings. Joints of a Trie is the nodes in a trie that have more than one child. Examples: Input: str = {"cat", "there", "caller", "their", "calling"} Output: l, a, e Explanation: root / \ c t | | a h / | | t l e | | \ l i r | \ | | e i r e
11 min read
Spell Checker using Trie
Given an array of strings str[] and a string key, the task is to check if the spelling of the key is correct or not. If found to be true, then print "YES". Otherwise, print the suggested correct spellings. Examples: Input:str[] = { “gee”, “geeks”, “ape”, “apple”, “geeksforgeeks” }, key = “geek” Output: geeks geeksforgeeks Explanation: The string "g
11 min read
Applications, Advantages and Disadvantages of Trie
Trie(pronounced as "try"): Trie(also known as the digital tree or prefix tree) is a sorted and efficient tree-based special data structure that is used to store and retrieve keys in a dataset of strings. The basic ideology behind this is retrieving information. It is based on the prefix of a string. It can be visualized as a graph consisting of nod
4 min read
Hash Table vs Trie
What is Hash Table? An array that stores pointers to records corresponding to a given element. An entry in the hash table is NIL if no existing element has a hash function value equal to the index for the entry. In simple terms, we can say that a hash table is a generalization of the array. Hash table gives the functionality in which a collection o
5 min read
Trie meaning in DSA
Trie data structure is defined as a Tree based data structure that is used for storing some collection of strings and performing efficient search operations on them. The word Trie is derived from reTRIEval, which means finding something or obtaining it. Representation of trie is similar to a tree data structure with a root node connected to its ele
2 min read
Program for assigning usernames using Trie
Suppose there is a queue of n users and your task is to assign a username to them. The system works in the following way. Every user has preferred login in the form of a string 's' s consists only of small case letters and numbers. User name is assigned in the following order s, s0, s1, s2....s11.... means first you check s if s is available assign
15+ min read
Construct a String from another String using Suffix Trie
A suffix tree is a data structure based on trie compression that stores all the suffixes of a given string. Apart from detecting patterns in strings, it has a range of applications in fields like bioinformatics, string algorithms, and data compression. Features of Suffix Trie:A Suffix Trie, commonly referred to as a suffix tree, is a data structure
15+ min read
Count of given Strings in 2D character Array using Trie
Counting the number of occurrences of a given string in a 2D character array using a Trie. Examples: Input: vector&lt;string&gt; grid = {"abcde", "fghij", "xyabc", "klmno",}; string word = "abc";Output: 2Explanation: abc occurs twice in "abcde", "xyabc" Input: vector&lt;string&gt; grid = {"abcde", "fghij", "xyabc", "klmno",}; string word = "klm";Ou
12 min read
Trie | (Delete)
In the previous post on trie we have described how to insert and search a node in trie. Here is an algorithm how to delete a node from trie.During delete operation we delete the key in bottom up manner using recursion. The following are possible conditions when deleting key from trie, Key may not be there in trie. Delete operation should not modify
11 min read
Longest prefix matching - A Trie based solution in Java
Given a dictionary of words and an input string, find the longest prefix of the string which is also a word in dictionary. Examples: Let the dictionary contains the following words: {are, area, base, cat, cater, children, basement} Below are some input/output examples: -------------------------------------- Input String Output ---------------------
4 min read
Pattern Searching using a Trie of all Suffixes
Problem Statement: Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] in txt[]. You may assume that n &gt; m.As discussed in the previous post, we discussed that there are two ways efficiently solve the above problem.1) Preprocess Pattern: KMP Algorithm, Rabin Kar
13 min read
Find shortest unique prefix for every word in a given list | Set 1 (Using Trie)
Given an array of words, find all shortest unique prefixes to represent each word in the given array. Assume that no word is prefix of another. Examples: Input: arr[] = {"zebra", "dog", "duck", "dove"} Output: dog, dov, du, z Explanation: dog =&gt; dog dove =&gt; dov duck =&gt; du zebra =&gt; z Input: arr[] = {"geeksgeeks", "geeksquiz", "geeksforge
11 min read
Overview of Graph, Trie, Segment Tree and Suffix Tree Data Structures
Introduction:Graph: A graph is a collection of vertices (nodes) and edges that represent relationships between the vertices. Graphs are used to model and analyze networks, such as social networks or transportation networks.Trie: A trie, also known as a prefix tree, is a tree-like data structure that stores a collection of strings. It is used for ef
10 min read
Longest Common Prefix using Trie
Given a set of strings, find the longest common prefix. Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”} Output : "gee" Input : {"apple", "ape", "april"} Output : "ap" Previous Approaches : Word by Word Matching , Character by Character Matching, Divide and Conquer , Binary Search. In this article, an approach using Trie date structure is discu
10 min read
Count of distinct substrings of a string using Suffix Trie
Given a string of length n of lowercase alphabet characters, we need to count total number of distinct substrings of this string. Examples: Input : str = “ababa” Output : 10 Total number of distinct substring are 10, which are, "", "a", "b", "ab", "ba", "aba", "bab", "abab", "baba" and "ababa"Recommended: Please solve it on “PRACTICE ” first, befor
11 min read
Boggle using Trie
Given a dictionary, a method to do a lookup in the dictionary and a M x N board where every cell has one character. Find all possible words that can be formed by a sequence of adjacent characters. Note that we can move to any of 8 adjacent characters, but a word should not have multiple instances of the same cell.Example: Input: dictionary[] = {"GE
15+ min read
Auto-complete feature using Trie
We are given a Trie with a set of strings stored in it. Now the user types in a prefix of his search query, we need to give him all recommendations to auto-complete his query based on the strings stored in the Trie. We assume that the Trie stores past searches by the users.For example if the Trie store {"abc", "abcd", "aa", "abbbaba"} and the User
10 min read