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

Trie Data Structure | Insert and Search

Last Updated : 12 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
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. Trie 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 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;
        }
    }
};
C
// Trie node structure
struct TrieNode {
    struct TrieNode* children[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->children[i] = NULL;
    }
    return node;
}
Java
public class TrieNode {
    
    // Array for child nodes of each node
    TrieNode[] children;
    
    // Used for indicating the end of a string
    boolean isEndOfWord;

    // Constructor
    public TrieNode() {
      
        // Initialize the wordEnd 
        // variable with false
        isEndOfWord = 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 
        children = new TrieNode[26];
    }
}
Python
class TrieNode:
    def __init__(self):
        self.children = [None] * 26
        self.isEndOfWord = False
C#
class TrieNode
{
    public TrieNode[] children = new TrieNode[26];
    public bool isLeaf = false;
}
JavaScript
class TrieNode {
    constructor() {
    
        // Initialize the child Node
        // array with 26 nulls
        this.children = Array(26).fill(null);
        
        // Initialize wordEnd to the false
        // indicating that no word ends here yet
        this.isEndOfWord = false;
    }
}

Insertion in Trie Data Structure – O(n) Time and O(1) 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).

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

C++
// Method to insert a key into the Trie
void insert(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) {
          
            // 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->children[c - 'a'] = newNode;
        }
      
        // Move the curr pointer to the
        // newly created node
        curr = curr->children[c - 'a'];
    }

    // Mark the end of the word
    curr->isLeaf = 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->children[index]) {
            curr->children[index] = getNode();
        }
        curr = curr->children[index];
        key++;
    }
    curr->isEndOfWord = true;
}
Java
// Method to insert a key into the Trie
static void insert(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.children[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.children[c - 'a'] = newNode;
        }

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

    // Mark the end of the word
    curr.isEndOfWord = true;
}
Python
# Method to insert a key into the Trie
def insert(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.children[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.children[index] = new_node

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

    # Mark the end of the word
    curr.isEndOfWord = True
C#
// Method to insert a key into the Trie
public static void Insert(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.children[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.children[c - 'a'] = newNode;
        }

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

    // Mark the end of the word
    curr.isLeaf = true;
}
JavaScript
// Method to insert a key into the Trie
function insert(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.children[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.children[index] = newNode;
        }

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

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

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

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


  • 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 given the implementation:

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
// 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->children[index]) {
            return false;
        }
        curr = curr->children[index];
        key++;
    }
    return (curr != NULL && curr->isEndOfWord);
}
Java
// Method to search a key in the Trie
static boolean search(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.children[c - 'a'] == null)
            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.isEndOfWord;
}
Python
# Method to search a key in the Trie
def search(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.children[index] is None:
            return False

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

    # Return true if the word exists 
    # and is marked as ending
    return curr.isEndOfWord
C#
// Method to search a key in the Trie
public static bool Search(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.children[c - 'a'] == null)
            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;
}
JavaScript
// Method to search a key in the Trie
function search(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.children[index] === null) 
            return false;

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

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

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

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

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

class TrieNode {
public:
  
    // Array for children nodes of each node
    TrieNode* children[26];

    // for end of word
    bool isLeaf;

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

// Method to insert a key into the Trie
void insert(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) {
          
            // 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->children[c - 'a'] = newNode;
        }
      
        // Move the curr pointer to the
        // newly created node
        curr = curr->children[c - 'a'];
    }

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

// Method to search a key in the Trie
bool search(TrieNode* root, const string& key) {

    if (root == nullptr) {
        return false;
    }
  
    // 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;
}

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

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

// Trie node structure
struct TrieNode {
    struct TrieNode* children[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->children[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->children[index]) {
            curr->children[index] = getNode();
        }
        curr = curr->children[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->children[index]) {
            return false;
        }
        curr = curr->children[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[] children = new TrieNode[26];

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

class GfG {

    // Method to insert a key into the Trie
    static void insert(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.children[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.children[c - 'a'] = newNode;
            }

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

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

    // Method to search a key in the Trie
    static boolean search(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.children[c - 'a'] == null) 
                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.isEndOfWord;
    }

    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) {
            insert(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 (search(root, s)) 
                System.out.println("Present");
            else 
                System.out.println("Not Present");        
        }
    }
}
Python
class TrieNode:

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

# Method to insert a key into the Trie
def insert(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.children[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.children[index] = new_node

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

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

# Method to search a key in the Trie
def search(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.children[index] is None:
            return False

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

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

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

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

class TrieNode {

    // Array to store children nodes (one for each letter 'a' to 'z')
    public TrieNode[] children = new TrieNode[26];

    // Boolean to mark the end of the word
    public bool isLeaf = false;
}

class GfG {

    // Method to insert a key into the Trie
    static void insert(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.children[c - 'a'] == null) {

                // If node for current character does not exist, create a new node
                TrieNode newNode = new TrieNode();
                curr.children[c - 'a'] = newNode;
            }

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

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

    // Method to search a key in the Trie
    static bool search(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.children[c - 'a'] == null)
                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;
    }

    // Main function to test the Trie functionality
    public static void Main()
    {
        // Create an example Trie
        TrieNode root = new TrieNode();
        List<string> arr = new List<string> { "and", "ant", "do", "geek", "dad", "ball" };

        // insert words into the Trie
        foreach (var s in arr)
        {
            insert(root, s);
        }

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

// Method to insert a key into the Trie
function insert(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.children[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.children[index] = newNode;
        }

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

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

// Method to search a key in the Trie
function search(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.children[index] === null) 
            return false;

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

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

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

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

Output
Key : do
Present
Key : gee
Not Present
Key : bat
Not Present

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: 


Master Data Structures and Algorithms at your own pace with our DSA Self-Paced course. In just 90 days, you’ll cover core concepts, solve real-world problems, and sharpen your problem-solving skills. Take the Three 90 Challenge: complete 90% of the course in 90 days and get a 90% refund. Stay motivated, track progress, and achieve DSA mastery. Start today!


Next Article

Similar Reads

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 : CPP class TrieNode{ public: // Use of shared_ptr for storing Children // Pointers of TrieNode shared_ptr children[ALPHABET_SIZE]; // Tracks whether If this Node
6 min read
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 hash
5 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 : foun
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
Commonly Asked Data Structure Interview Questions on Heap Data Structure
A heap is a complete binary tree that maintains a specific order, making it efficient for priority-based operations. It is mainly of two types:Min Heap: The smallest value is at the root, and each parent is smaller than its children.Max Heap: The largest value is at the root, and each parent is larger than its children.Heaps are commonly stored as
4 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
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
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
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