(Translated by https://www.hiragana.jp/)
Trie Data Structure - GeeksforGeeks
Open In App

Trie Data Structure

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this article, we will explore the insertion and search operations and prefix searches in Trie Data Structure.

Triedatastructure1
Trie Data Structure


Representation of Trie Node

  • Trie data structure consists of nodes connected by edges.
  • Each node represents a character or a part of a string.
  • The root node acts as a starting point and does not store any character.
C++
class TrieNode {
public:

    // pointer array for child nodes of each node
    TrieNode* children[26];

    // Used for indicating ending of string
    bool isLeaf;

    TrieNode() {
      
        // initialize the wordEnd variable with false
        // initialize every index of childNode array with NULL
        isLeaf = false;
        for (int i = 0; i < 26; i++) {
            children[i] = nullptr;
        }
    }
};
Java Python C# JavaScript

Insertion in Trie Data Structure - O(n) Time and O(n) Space

Insert Operation in Trie Data Structure

Inserting "and" in Trie data structure:

  • Start at the root node: The root node has no character associated with it and its wordEnd value is 0, indicating no complete word ends at this point.
  • First character "a": Calculate the index using 'a' - 'a' = 0. Check if the child[0] is null. Since it is, create a new TrieNode with the character "a", wordEnd set to 0, and an empty array of pointers. Move to this new node.
  • Second character "n": Calculate the index using 'n' - 'a' = 13. Check if child[13] is null. It is, so create a new TrieNode with the character "n", wordEnd set to 0, and an empty array of pointers. Move to this new node.
  • Third character "d": Calculate the index using 'd' - 'a' = 3. Check if child[3] is null. It is, so create a new TrieNode with the character "d", wordEnd set to 1 (indicating the word "and" ends here).

Inserting "ant" in Trie data structure:

  • Start at the root node: Root node doesn't contain any data but it keep track of every first character of every string that has been inserted.
  • First character "a": Calculate the index using 'a' - 'a' = 0. Check if the child[0] is null. We already have the "a" node created from the previous insertion. so move to the existing "a" node.
  • First character "n": Calculate the index using 'n' - 'a' = 13. Check if child[13] is null. It's not, so move to the existing "n" node.
  • Second character "t": Calculate the index using 't' - 'a' = 19. Check if child[19] is null. It is, so create a new TrieNode with the character "t", wordEnd set to 1 (indicating the word "ant" ends here).
C++
C Java Python C# JavaScript

Time Complexity: O(n), where n is the length of the word to insert.
Auxiliary Space: O(n)

Searching in Trie Data Structure - O(n) Time and O(1) Space

Searching for a key in Trie data structure is similar to its insert operation. However, It only compares the characters and moves down. The search can terminate due to the end of a string or lack of key in the trie. 

Here's a visual representation of searching word "dad" in Trie data structure:
Let's assume that we have successfully inserted the words "and", "ant", and "dad" into our Trie, and we have to search for specific words within the Trie data structure. Let's try searching for the word "dad":

Search Operation in Trie Data Structure


Here's a visual representation of searching word "dad" in Trie data structure:
Let's assume that we have successfully inserted the words "and", "ant", and "dad" into our Trie, and we have to search for specific words within the Trie data structure. Let's try searching for the word "dad":

  • We start at the root node.
  • We follow the branch corresponding to the character 'd'.
  • We follow the branch corresponding to the character 'a'.
  • We follow the branch corresponding to the character 'd'.
  • We reach the end of the word and wordEnd flag is 1.
  • This means that "dad" is present in the Trie.


C++
// Method to search a key in the Trie
bool search(TrieNode* root, const string& key) {
  
    // Initialize the curr pointer with the root node
    TrieNode* curr = root;

    // Iterate across the length of the string
    for (char c : key) {
      
        // Check if the node exists for the 
        // current character in the Trie
        if (curr->children[c - 'a'] == nullptr) 
            return false;
        
        // Move the curr pointer to the 
        // already existing node for the 
        // current character
        curr = curr->children[c - 'a'];
    }

    // Return true if the word exists 
    // and is marked as ending
    return curr->isLeaf;
}
C Java Python C# JavaScript

Time Complexity: O(n), where n is the length of the word to search.
Auxiliary Space: O(1)

Prefix Searching in Trie Data Structure - O(n) Time and O(1) Space

Searching for a prefix in a Trie data structure is similar to searching for a key, but the search does not need to reach the end of the word. Instead, we stop as soon as we reach the end of the prefix or if any character in the prefix doesn't exist in the Trie.

Here's a visual representation of prefix searching for the word 'da' in the Trie data structure:
Let's assume that we have successfully inserted the words 'and', 'ant', and 'dad' into our Trie. Now, let's search for the prefix 'da' within the Trie data structure.

11
  • We start at the root node.
  • We follow the branch corresponding to the character 'd'.
  • We move to the node corresponding to the character 'a'.
  • We reach the end of the prefix "da". Since we haven't encountered any missing characters along the way, we return true.
C++
// Method to Seach Prefix key in Trie
bool isPrefix(TrieNode *root, string &key)
{
    TrieNode *current = root;
    for (char c : key)
    {
        int index = c - 'a';

        // If character doesn't exist, return false
        if (current->children[index] == nullptr)
        {
            return false;
        }
        current = current->children[index];
    }

    return true;
}
Java Python C# JavaScript

Time Complexity: O(n), where n is the length of the word to search.
Auxiliary Space: O(1)

Implementation of Insert, Search and Prefix Searching Operations in Trie Data Structure

Now that we've learned how to insert words into a Trie, search for complete words, and perform prefix searches, let's do some hands-on practice.

We'll start by inserting the following words into the Trie: ["and", "ant", "do", "dad"].
Then, we'll search for the presence of these words: ["do", "gee", "bat"].
Finally, we'll check for the following prefixes: ["ge", "ba", "do", "de"].

Steps-by-step approach:

  • Create a root node with the help of TrieNode() constructor.
  • Store a collection of strings that have to be inserted in the Trie in a vector of strings say, arr.
  • Inserting all strings in Trie with the help of the insertKey() function,
  • Search strings with the help of searchKey() function.
  • Prefix searching with the help of isPrefix() function.
C++
Java Python C# JavaScript

Output
true false false 
false false true false 

Complexity Analysis of Trie Data Structure

OperationTime Complexity
InsertionO(n) Here n is the length of the string inserted
SearchingO(n) Here n is the length of the string searched

Prefix Searching

O(n) Here n is the length of the string searched

Related Articles: 

Practice Problems: 


Introduction to Trie Data Structure
Visit Course explore course icon
Video Thumbnail

Introduction to Trie Data Structure

Video Thumbnail

Trie (Representation, Search & Insert)

Similar Reads