The Wayback Machine - https://web.archive.org/web/20240823080827/https://www.geeksforgeeks.org/trie-insert-and-search/
Open In App

Trie Data Structure | Insert and Search

Last Updated : 07 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The Trie data structure is a tree-like data structure used for storing a dynamic set of strings. It is commonly used for efficient retrieval and storage of keys in a large dataset. The structure supports operations such as insertion, search, and deletion of keys, making it a valuable tool in fields like computer science and information retrieval. In this article we are going to explore insertion and search operation in Trie Data Structure.

Trie data structure

Trie data structure

Representation of of Trie Node:

A Trie data structure consists of nodes connected by edges. Each node represents a character or a part of a string. The root node, the starting point of the Trie, represents an empty string. Each edge emanating from a node signifies a specific character. The path from the root to a node represents the prefix of a string stored in the Trie.

A simple structure to represent nodes of the English alphabet can be as follows.

C++
struct TrieNode {

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

    // Used for indicating ending of string
    bool wordEnd;

    TrieNode()
    {
        // constructor
        // initialize the wordEnd variable with false
        // initialize every index of childNode array with
        // NULL
        wordEnd = false;
        for (int i = 0; i < 26; i++) {
            child[i] = NULL;
        }
    }
};
C
// Trie node structure
struct TrieNode {
    struct TrieNode* child[26];
    bool isEndOfWord;
};

// Function to create a new Trie node
struct TrieNode* getNode() {
    struct TrieNode* node = 
      (struct TrieNode*)malloc(sizeof(struct TrieNode));
    node->isEndOfWord = false;
    for (int i = 0; i < 26; i++) {
        node->child[i] = NULL;
    }
    return node;
}
Java
public class TrieNode {
    
    // Array for child nodes of each node
    TrieNode[] child;
    
    // Used for indicating the end of a string
    boolean wordEnd;

    // Constructor
    public TrieNode() {
      
        // Initialize the wordEnd 
        // variable with false
        wordEnd = false;

        // Initialize every index of 
        // the child array with null
        // In Java, we do not have to 
        // explicitely assign null as 
        // the values are by default 
        // assigned as null 
        child = new TrieNode[26];
    }
}
Python
class TrieNode:
    def __init__(self):
        self.child = [None] * 26
        self.wordEnd = False
C#
class TrieNode
{
    public TrieNode[] Child = new TrieNode[26];
    public bool WordEnd = false;
}
JavaScript
class TrieNode {
    constructor() {
    
        // Initialize the child Node
        // array with 26 nulls
        this.child = Array(26).fill(null);
        
        // Initialize wordEnd to the false
        // indicating that no word ends here yet
        this.wordEnd = false;
    }
}

Insertion in Trie Data Structure:

Let’s walk through the process of inserting the words into a Trie data structure. We have already cover the basics of Trie and its node structure.

Here’s a visual representation of inserting the words “and” and “ant” into a Trie data structure:


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).

Below is the implementation of insertion of strings in Trie data structure:

Time Complexity: O(number of words * maxLengthOfWord)
Auxiliary Space: O(number of words * maxLengthOfWord)

Searching in Trie Data Structure:

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. 

Steps by step approach for searching in Trie Data structure:

  • Start at the root node. This is the starting point for all searches within the Trie.
  • Traverse the Trie based on the characters of the word you are searching for. For each character, follow the corresponding branch in the Trie. If the branch doesn’t exist, the word is not present in the Trie.
  • If you reach the end of the word and the wordEnd flag is set to 1, the word has been found.
  • If you reach the end of the word and the wordEnd flag is 0, the word is not present in the Trie, even though it shares a prefix with an existing word.

Below is the implementation of the above approach:

C++
// Method to insert a key into the Trie
void insertKey(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->child[c - 'a'] == nullptr) {
          
            // If node for current character does 
            // not exist then make a new node
            TrieNode* newNode = new TrieNode();
          
            // Keep the reference for the newly
            // created node
            curr->child[c - 'a'] = newNode;
        }
      
        // Move the curr pointer to the
        // newly created node
        curr = curr->child[c - 'a'];
    }

    // Mark the end of the word
    curr->wordEnd = true;
}
C
// Function to insert a key into the Trie
void insert(struct TrieNode* root, const char* key) {
    struct TrieNode* curr = root;
    while (*key) {
        int index = *key - 'a';
        if (!curr->child[index]) {
            curr->child[index] = getNode();
        }
        curr = curr->child[index];
        key++;
    }
    curr->isEndOfWord = true;
}
Java
// Method to insert a key into the Trie
static void insertKey(TrieNode root, String key)
{

    // Initialize the curr pointer with the root node
    TrieNode curr = root;

    // Iterate across the length of the string
    for (char c : key.toCharArray()) {

        // Check if the node exists for the
        // current character in the Trie
        if (curr.child[c - 'a'] == null) {

            // If node for current character does
            // not exist then make a new node
            TrieNode newNode = new TrieNode();

            // Keep the reference for the newly
            // created node
            curr.child[c - 'a'] = newNode;
        }

        // Move the curr pointer to the
        // newly created node
        curr = curr.child[c - 'a'];
    }

    // Mark the end of the word
    curr.wordEnd = true;
}
Python
# Method to insert a key into the Trie
def insert_key(root, key):

    # Initialize the curr pointer with the root node
    curr = root

    # Iterate across the length of the string
    for c in key:

        # Check if the node exists for the
        # current character in the Trie
        index = ord(c) - ord('a')
        if curr.child[index] is None:

            # If node for current character does
            # not exist then make a new node
            new_node = TrieNode()

            # Keep the reference for the newly
            # created node
            curr.child[index] = new_node

        # Move the curr pointer to the
        # newly created node
        curr = curr.child[index]

    # Mark the end of the word
    curr.word_end = True
C#
// Method to insert a key into the Trie
public static void InsertKey(TrieNode root, string key)
{
    // Initialize the curr pointer with the root node
    TrieNode curr = root;

    // Iterate across the length of the string
    foreach(char c in key)
    {
        // Check if the node exists for the current
        // character in the Trie
        if (curr.Child[c - 'a'] == null) {
            // If node for current character does
            // not exist then make a new node
            TrieNode newNode = new TrieNode();

            // Keep the reference for the newly created node
            curr.Child[c - 'a'] = newNode;
        }

        // Move the curr pointer to the newly created node
        curr = curr.Child[c - 'a'];
    }

    // Mark the end of the word
    curr.WordEnd = true;
}
JavaScript
// Method to insert a key into the Trie
function insertKey(root, key) {

    // Initialize the curr pointer with the root node
    let curr = root;

    // Iterate across the length of the string
    for (let c of key) {

        // Check if the node exists for the 
        // current character in the Trie
        let index = c.charCodeAt(0) - 'a'.charCodeAt(0);
        if (curr.child[index] === null) {

            // If node for current character does 
            // not exist then make a new node
            let newNode = new TrieNode();

            // Keep the reference for the newly
            // created node
            curr.child[index] = newNode;
        }

        // Move the curr pointer to the
        // newly created node
        curr = curr.child[index];
    }

    // Mark the end of the word
    curr.wordEnd = true;
}

Output
Query String: do
The query string is present in the Trie
Query String: geek
The query string is present in the Trie
Query String: bat
The query string is not present 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


  • 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.

Below is the implementation of searching strings in Trie Data Structure:

C++
// Method to search a key in the Trie
bool searchKey(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->child[c - 'a'] == nullptr) 
            return false;
        
        // Move the curr pointer to the 
        // already existing node for the 
        // current character
        curr = curr->child[c - 'a'];
    }

    // Return true if the word exists 
    // and is marked as ending
    return curr->wordEnd;
}
C
// Function to search a key in the Trie
bool search(struct TrieNode* root, const char* key) {
    struct TrieNode* curr = root;
    while (*key) {
        int index = *key - 'a';
        if (!curr->child[index]) {
            return false;
        }
        curr = curr->child[index];
        key++;
    }
    return (curr != NULL && curr->isEndOfWord);
}
Java
// Method to search a key in the Trie
static boolean searchKey(TrieNode root, String key)
{

    // Initialize the curr pointer with the root node
    TrieNode curr = root;

    // Iterate across the length of the string
    for (char c : key.toCharArray()) {

        // Check if the node exists for the
        // current character in the Trie
        if (curr.child[c - 'a'] == null)
            return false;

        // Move the curr pointer to the
        // already existing node for the
        // current character
        curr = curr.child[c - 'a'];
    }

    // Return true if the word exists
    // and is marked as ending
    return curr.wordEnd;
}
Python
# Method to search a key in the Trie
def search_key(root, key):

    # Initialize the curr pointer with the root node
    curr = root

    # Iterate across the length of the string
    for c in key:

        # Check if the node exists for the 
        # current character in the Trie
        index = ord(c) - ord('a')
        if curr.child[index] is None:
            return False

        # Move the curr pointer to the 
        # already existing node for the 
        # current character
        curr = curr.child[index]

    # Return true if the word exists 
    # and is marked as ending
    return curr.word_end
C#
// Method to search a key in the Trie
public static bool SearchKey(TrieNode root, string key)
{
    // Initialize the curr pointer with the root node
    TrieNode curr = root;

    // Iterate across the length of the string
    foreach(char c in key)
    {
        // Check if the node exists for the current
        // character in the Trie
        if (curr.Child[c - 'a'] == null)
            return false;

        // Move the curr pointer to the already
        // existing node for the current character
        curr = curr.Child[c - 'a'];
    }

    // Return true if the word exists and
    // is marked as ending
    return curr.WordEnd;
}
JavaScript
// Method to search a key in the Trie
function searchKey(root, key) {

    // Initialize the curr pointer with the root node
    let curr = root;

    // Iterate across the length of the string
    for (let c of key) {

        // Check if the node exists for the 
        // current character in the Trie
        let index = c.charCodeAt(0) - 'a'.charCodeAt(0);
        if (curr.child[index] === null) 
            return false;

        // Move the curr pointer to the 
        // already existing node for the 
        // current character
        curr = curr.child[index];
    }

    // Return true if the word exists 
    // and is marked as ending
    return curr.wordEnd;
}

Time Complexity: O(number of words * maxLengthOfWord)
Auxiliary Space: O(number of words * maxLengthOfWord)

Implementation of Insert and Search Operations in Trie Data Structure:

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 insert_key() function,
  • Search strings with the help of search_key() function.

Below is the implementation of the above approach:

C++
#include <iostream>
#include <vector>
#include <string>
using namespace std;

struct TrieNode {
  
    // Array for child nodes of each node
    TrieNode* child[26];

    // for end of word
    bool wordEnd;

    TrieNode() {
        wordEnd = false;
        for (int i = 0; i < 26; i++) {
            child[i] = nullptr;
        }
    }
};

// Method to insert a key into the Trie
void insertKey(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->child[c - 'a'] == nullptr) {
          
            // If node for current character does 
            // not exist then make a new node
            TrieNode* newNode = new TrieNode();
          
            // Keep the reference for the newly
            // created node
            curr->child[c - 'a'] = newNode;
        }
      
        // Move the curr pointer to the
        // newly created node
        curr = curr->child[c - 'a'];
    }

    // Mark the end of the word
    curr->wordEnd = true;
}

// Method to search a key in the Trie
bool searchKey(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->child[c - 'a'] == nullptr) 
            return false;
        
        // Move the curr pointer to the 
        // already existing node for the 
        // current character
        curr = curr->child[c - 'a'];
    }

    // Return true if the word exists 
    // and is marked as ending
    return curr->wordEnd;
}

int main() {
  
    // Create am example Trie
    TrieNode* root = new TrieNode();
    vector<string> arr = 
      {"and", "ant", "do", "geek", "dad", "ball"};
    for (const string& s : arr) {
        insertKey(root, s);
    }

    // One by one search strings
    vector<string> searchKeys = {"do", "gee", "bat"};
    for (string& s : searchKeys) {
        cout << "Key : " << s << "\n";
        if (searchKey(root, s)) 
            cout << "Present\n";
        else 
            cout << "Not Present\n";        
    }
  
    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define ALPHABET_SIZE 26

// Trie node structure
struct TrieNode {
    struct TrieNode* child[ALPHABET_SIZE];
    bool isEndOfWord;
};

// Function to create a new Trie node
struct TrieNode* getNode() {
    struct TrieNode* node = 
      (struct TrieNode*)malloc(sizeof(struct TrieNode));
    node->isEndOfWord = false;
    for (int i = 0; i < ALPHABET_SIZE; i++) {
        node->child[i] = NULL;
    }
    return node;
}

// Function to insert a key into the Trie
void insert(struct TrieNode* root, const char* key) {
    struct TrieNode* curr = root;
    while (*key) {
        int index = *key - 'a';
        if (!curr->child[index]) {
            curr->child[index] = getNode();
        }
        curr = curr->child[index];
        key++;
    }
    curr->isEndOfWord = true;
}

// Function to search a key in the Trie
bool search(struct TrieNode* root, const char* key) {
    struct TrieNode* curr = root;
    while (*key) {
        int index = *key - 'a';
        if (!curr->child[index]) {
            return false;
        }
        curr = curr->child[index];
        key++;
    }
    return (curr != NULL && curr->isEndOfWord);
}

// Main function to test the Trie implementation
int main() {
    // Create an example Trie
    char* keys[] = {"and", "ant", "do", "geek", "dad", "ball"};
    int n = sizeof(keys) / sizeof(keys[0]);

    struct TrieNode* root = getNode();
    for (int i = 0; i < n; i++) {
        insert(root, keys[i]);
    }

    // One by one search strings
    char* searchKeys[] = {"do", "gee", "bat"};
    int m = sizeof(searchKeys) / sizeof(searchKeys[0]);

    for (int i = 0; i < m; i++) {
        printf("Key : %s\n", searchKeys[i]);
        if (search(root, searchKeys[i])) {
            printf("Present\n");
        } else {
            printf("Not Present\n");
        }
    }

    return 0;
}
Java
import java.util.Arrays;
import java.util.List;

class TrieNode {

    // Java Makes sure that all 26 are null
    TrieNode[] child = new TrieNode[26];

    // for end of word
    boolean wordEnd = false;
}

class GfG {

    // Method to insert a key into the Trie
    static void insertKey(TrieNode root, String key) {

        // Initialize the curr pointer with the root node
        TrieNode curr = root;

        // Iterate across the length of the string
        for (char c : key.toCharArray()) {

            // Check if the node exists for the 
            // current character in the Trie
            if (curr.child[c - 'a'] == null) {

                // If node for current character does 
                // not exist then make a new node
                TrieNode newNode = new TrieNode();

                // Keep the reference for the newly
                // created node
                curr.child[c - 'a'] = newNode;
            }

            // Move the curr pointer to the
            // newly created node
            curr = curr.child[c - 'a'];
        }

        // Mark the end of the word
        curr.wordEnd = true;
    }

    // Method to search a key in the Trie
    static boolean searchKey(TrieNode root, String key) {

        // Initialize the curr pointer with the root node
        TrieNode curr = root;

        // Iterate across the length of the string
        for (char c : key.toCharArray()) {

            // Check if the node exists for the 
            // current character in the Trie
            if (curr.child[c - 'a'] == null) 
                return false;

            // Move the curr pointer to the 
            // already existing node for the 
            // current character
            curr = curr.child[c - 'a'];
        }

        // Return true if the word exists 
        // and is marked as ending
        return curr.wordEnd;
    }

    public static void main(String[] args) {

        // Create an example Trie
        TrieNode root = new TrieNode();
        List<String> arr = Arrays.asList(
            "and", "ant", "do", "geek", "dad", "ball");
        for (String s : arr) {
            insertKey(root, s);
        }

        // One by one search strings
        List<String> searchKeys = 
              Arrays.asList("do", "gee", "bat");
        for (String s : searchKeys) {
            System.out.println("Key : " + s);
            if (searchKey(root, s)) 
                System.out.println("Present");
            else 
                System.out.println("Not Present");        
        }
    }
}
Python
class TrieNode:

    def __init__(self):
      
        # Array for child nodes of each node
        self.child = [None] * 26
        
        # for end of word
        self.word_end = False

# Method to insert a key into the Trie
def insert_key(root, key):

    # Initialize the curr pointer with the root node
    curr = root

    # Iterate across the length of the string
    for c in key:

        # Check if the node exists for the 
        # current character in the Trie
        index = ord(c) - ord('a')
        if curr.child[index] is None:

            # If node for current character does 
            # not exist then make a new node
            new_node = TrieNode()

            # Keep the reference for the newly
            # created node
            curr.child[index] = new_node

        # Move the curr pointer to the
        # newly created node
        curr = curr.child[index]

    # Mark the end of the word
    curr.word_end = True

# Method to search a key in the Trie
def search_key(root, key):

    # Initialize the curr pointer with the root node
    curr = root

    # Iterate across the length of the string
    for c in key:

        # Check if the node exists for the 
        # current character in the Trie
        index = ord(c) - ord('a')
        if curr.child[index] is None:
            return False

        # Move the curr pointer to the 
        # already existing node for the 
        # current character
        curr = curr.child[index]

    # Return true if the word exists 
    # and is marked as ending
    return curr.word_end

# Create an example Trie
root = TrieNode()
arr = ["and", "ant", "do", "geek", "dad", "ball"]
for s in arr:
    insert_key(root, s)

# One by one search strings
search_keys = ["do", "gee", "bat"]
for s in search_keys:
    print(f"Key : {s}")
    if search_key(root, s):
        print("Present")
    else:
        print("Not Present")
C#
using System;
using System.Collections.Generic;

class TrieNode
{
    public TrieNode[] Child = new TrieNode[26];
    public bool WordEnd = false;
}

public class GfG
{
    // Method to insert a key into the Trie
    public static void InsertKey(TrieNode root, string key)
    {
        // Initialize the curr pointer with the root node
        TrieNode curr = root;

        // Iterate across the length of the string
        foreach (char c in key)
        {
            // Check if the node exists for the current 
            // character in the Trie
            if (curr.Child[c - 'a'] == null)
            {
                // If node for current character does
                // not exist then make a new node
                TrieNode newNode = new TrieNode();

                // Keep the reference for the newly created node
                curr.Child[c - 'a'] = newNode;
            }

            // Move the curr pointer to the newly created node
            curr = curr.Child[c - 'a'];
        }

        // Mark the end of the word
        curr.WordEnd = true;
    }

    // Method to search a key in the Trie
    public static bool SearchKey(TrieNode root, string key)
    {
        // Initialize the curr pointer with the root node
        TrieNode curr = root;

        // Iterate across the length of the string
        foreach (char c in key)
        {
            // Check if the node exists for the current character in the Trie
            if (curr.Child[c - 'a'] == null)
                return false;

            // Move the curr pointer to the already 
            // existing node for the current character
            curr = curr.Child[c - 'a'];
        }

        // Return true if the word exists and 
        // is marked as ending
        return curr.WordEnd;
    }

    public static void Main(string[] args)
    {
        // Create an example Trie
        TrieNode root = new TrieNode();
        List<string> arr = 
          new List<string> { "and", "ant", "do", "geek", "dad", "ball" };
        foreach (string s in arr)
        {
            InsertKey(root, s);
        }

        // One by one search strings
        List<string> searchKeys = 
             new List<string> { "do", "gee", "bat" };
        foreach (string s in searchKeys)
        {
            Console.WriteLine("Key : " + s);
            if (SearchKey(root, s))
                Console.WriteLine("Present");
            else
                Console.WriteLine("Not Present");
        }
    }
}
JavaScript
class TrieNode {
    constructor() {
    
        // Array for child nodes of each node
        this.child = new Array(26).fill(null);
        
        // for end of word
        this.wordEnd = false;
    }
}

// Method to insert a key into the Trie
function insertKey(root, key) {

    // Initialize the curr pointer with the root node
    let curr = root;

    // Iterate across the length of the string
    for (let c of key) {

        // Check if the node exists for the 
        // current character in the Trie
        let index = c.charCodeAt(0) - 'a'.charCodeAt(0);
        if (curr.child[index] === null) {

            // If node for current character does 
            // not exist then make a new node
            let newNode = new TrieNode();

            // Keep the reference for the newly
            // created node
            curr.child[index] = newNode;
        }

        // Move the curr pointer to the
        // newly created node
        curr = curr.child[index];
    }

    // Mark the end of the word
    curr.wordEnd = true;
}

// Method to search a key in the Trie
function searchKey(root, key) {

    // Initialize the curr pointer with the root node
    let curr = root;

    // Iterate across the length of the string
    for (let c of key) {

        // Check if the node exists for the 
        // current character in the Trie
        let index = c.charCodeAt(0) - 'a'.charCodeAt(0);
        if (curr.child[index] === null) 
            return false;

        // Move the curr pointer to the 
        // already existing node for the 
        // current character
        curr = curr.child[index];
    }

    // Return true if the word exists 
    // and is marked as ending
    return curr.wordEnd;
}

// Create an example Trie
let root = new TrieNode();
let arr = 
   ["and", "ant", "do", "geek", "dad", "ball"];
for (let s of arr) {
    insertKey(root, s);
}

// One by one search strings
let searchKeys = ["do", "gee", "bat"];
for (let s of searchKeys) {
    console.log("Key :", s);
    if (searchKey(root, s)) 
        console.log("Present");
    else 
        console.log("Not Present");        
}

Output
Query String: do
The query string is present in the Trie
Query String: geek
The query string is present in the Trie
Query String: bat
The query string is not present in the Trie

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

Related Articles: 

Practice Problems: 



Similar Reads

Design a data structure that supports insert, delete, search and getRandom in constant time
Design a data structure that supports the following operations in O(1) time. insert(x): Inserts an item x to the data structure if not already present.remove(x): Removes item x from the data structure if present. search(x): Searches an item x in the data structure.getRandom(): Returns a random element from the current set of elements We can use has
5 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
Advantages of Trie Data Structure
Introduction: Trie (also known as prefix tree) is a tree-based data structure that is used to store an associative array where the keys are sequences (usually strings). Some advantages of using a trie data structure include:Fast search: Tries support fast search operations, as we can search for a key by traversing down the tree from the root, and t
8 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
Static Data Structure vs Dynamic Data Structure
Data structure is a way of storing and organizing data efficiently such that the required operations on them can be performed be efficient with respect to time as well as memory. Simply, Data Structure are used to reduce complexity (mostly the time complexity) of the code. Data structures can be two types : 1. Static Data Structure 2. Dynamic Data
4 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
Design a data structure that supports insert, delete, getRandom in O(1) with duplicates
Design a Data Structure that can support the following operations in O(1) Time Complexity. insert(x): Inserts x in the data structure. Returns True if x was not present and False if it was already present.remove(x): Removes x from the data structure, if present.getRandom(): Returns any value present in the stream randomly. The probability of each e
9 min read
Add and Search Word - Data Structure Design
Design a data structure GFGDictionary that enables to support the feature of adding new words and searching for words. The GFGDictionary class should have the following implementation: GFGDictionary(): constructor to initialize the objectvoid insertWord(word): function to insert word into the data structure.bool findWord(word): function to return t
4 min read
2-3 Trees | (Search, Insert and Deletion)
In binary search trees we have seen the average-case time for operations like search/insert/delete is O(log N) and the worst-case time is O(N) where N is the number of nodes in the tree. Like other Trees include AVL trees, Red Black Tree, B tree, 2-3 Tree is also a height balanced tree. The time complexity of search/insert/delete is O(log N) . A 2-
4 min read
Implementation of Search, Insert and Delete in Treap
We strongly recommend to refer set 1 as a prerequisite of this post.Treap (A Randomized Binary Search Tree)In this post, implementations of search, insert and delete are discussed.Search: Same as standard BST search. Priority is not considered for search. C/C++ Code // C function to search a given key in a given BST TreapNode* search(TreapNode* roo
15+ min read
Search, Insert, and Delete in an Sorted Array | Array Operations
How to Search in a Sorted Array? In a sorted array, the search operation can be performed by using binary search. Below is the implementation of the above approach: C/C++ Code // C++ program to implement binary search in sorted array #include &lt;bits/stdc++.h&gt; using namespace std; int binarySearch(int arr[], int low, int high, int key) { if (hi
15+ min read
Search, Insert, and Delete in an Unsorted Array | Array Operations
In this post, a program to search, insert, and delete operations in an unsorted array is discussed. Search Operation:In an unsorted array, the search operation can be performed by linear traversal from the first element to the last element.  Coding implementation of the search operation:[GFGTABS] C++ // C++ program to implement linear // search in
15+ min read
Introduction to Finger search tree Data Structure
A finger search tree is a data structure that is designed to allow for efficient search and access of data in a set or a sequence. It is a type of binary search tree that uses a "finger" or a reference to a particular element in the tree to quickly find and retrieve other elements. In this article, we will explore the types, advantages, disadvantag
15+ 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
How to insert a node in Binary Search Tree using Iteration
You are given a binary search tree (BST) and a value to insert into the tree. Print inorder traversal of the BST after the insertion.Example: Input:To the given BST insert 40 Output: Explanation:The new node 40 is a leaf node. Start searching from the root till a leaf node is hit, i.e while searching if a new value is greater than current node move
10 min read
Search insert position of K in a sorted array
Given a sorted array arr[] consisting of N distinct integers and an integer K, the task is to find the index of K, if it's present in the array arr[]. Otherwise, find the index where K must be inserted to keep the array sorted. Examples: Input: arr[] = {1, 3, 5, 6}, K = 5Output: 2Explanation: Since 5 is found at index 2 as arr[2] = 5, the output is
9 min read
Binary Search Tree insert with Parent Pointer
We have discussed simple BST insert. How to insert in a tree where parent pointer needs to be maintained. Parent pointers are helpful to quickly find ancestors of a node, LCA of two nodes, successor of a node, etc. In recursive calls of simple insertion, we return pointer of root of subtree created in a subtree. So the idea is to store this pointer
9 min read
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
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
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
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
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
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
three90RightbarBannerImg