Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Counting the number of words in a Trie
Next article icon

Counting the number of words in a Trie

Last Updated : 14 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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
# Python implementation to count words in a trie      # Alphabet size (# of symbols) from pickle import NONE  ALPHABET_SIZE = 26  # Trie node class TrieNode:              def __init__(self):         # isLeaf is true if the node represents         # end of a word         self.isLeaf = False         self.children = [None for i in range(ALPHABET_SIZE)]       root = TrieNode()          # If not present, inserts key into trie # If the key is prefix of trie node, just # marks leaf node def insert(key):      length = len(key)          pCrawl = root          for level in range(length):          index = ord(key[level]) - ord('a')         if (pCrawl.children[index] == None):             pCrawl.children[index] = TrieNode()                  pCrawl = pCrawl.children[index]              # mark last node as leaf     pCrawl.isLeaf = True       # Function to count number of words def wordCount(root):      result = 0          # Leaf denotes end of a word     if (root.isLeaf == True):         result += 1              for i in range(ALPHABET_SIZE):             if (root.children[i] != None):             result += wordCount(root.children[i])              return result      # Driver Program  # Input keys (use only 'a' through 'z' # and lower case) keys = ["the", "a", "there", "answer", "any", "by", "bye", "their"];  root = TrieNode()  # Construct Trie for i in range(len(keys)):     insert(keys[i])      print(wordCount(root))  # This code is contributed by shinjanpatra 
C#
// C# implementation to count words in a trie  using System;  public class Words_in_trie  {           // Alphabet size (# of symbols)      static readonly int ALPHABET_SIZE = 26;           // Trie node      public class TrieNode      {          public TrieNode[] children = new TrieNode[ALPHABET_SIZE];                   // isLeaf is true if the node represents          // end of a word          public bool isLeaf;                   public 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[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 code      public static void Main()      {          // 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]);               Console.WriteLine(wordCount(root));      }  }   /* This code contributed by PrinciRaj1992 */ 
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)


Next Article
Counting the number of words in a Trie

R

Rohit Thapliyal
Improve
Article Tags :
  • Tree
  • Advanced Data Structure
  • DSA
  • Trie
Practice Tags :
  • Advanced Data Structure
  • Tree
  • Trie

Similar Reads

    Lex Program to count number of words
    Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language. Prerequisite: Flex (Fast lexical Analyzer Generator) Examp
    1 min read
    Count words present in a string
    Given an array of words and a string, we need to count all words that are present in given string. Examples: Input : words[] = { "welcome", "to", "geeks", "portal"} str = "geeksforgeeks is a computer science portal for geeks." Output : 2 Two words "portal" and "geeks" is present in str. Input : word
    6 min read
    Count occurrences of a word in string
    Given a two strings s and word. The task is to count the number of occurrences of the string word in the string s.Note: The string word should appear in s as a separate word, not as a substring within other words.Examples: Input: s = "GeeksforGeeks A computer science portal for geeks", word = "porta
    11 min read
    Count words in a given string
    Given a string, count the number of words in it. The words are separated by the following characters: space (' ') or new line ('\n') or tab ('\t') or a combination of these. Recommended PracticeCount number of wordsTry It!Method 1: The idea is to maintain two states: IN and OUT. The state OUT indica
    15+ min read
    Count number of times given sentence can be fitted on screen
    Given a screen with dimensions rows*cols, and a sentence represented as a list of strings. The task is to return the number of times the given sentence can be fitted on the screen. The following constraints must be met: The order of words in the sentence must remain unchanged.A word cannot be split
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences