Open In App

Advantages of Trie Data Structure

Last Updated : 29 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Introduction:

  1. 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:
  2. Fast search: Tries support fast search operations, as we can search for a key by traversing down the tree from the root, and the search time is directly proportional to the length of the key. This makes tries an efficient data structure for searching for keys in a large dataset.
  3. Space-efficient: Tries are space-efficient because they store only the characters that are present in the keys, and not the entire key itself. This makes tries an ideal data structure for storing large dictionaries or lexicons.
  4. Auto-complete: Tries are widely used in applications that require auto-complete functionality, such as search engines or predictive text input.
  5. Efficient insertion and deletion: Tries support fast insertion and deletion of keys, as we can simply add or delete nodes from the tree as needed.
  6. Efficient sorting: Tries can be used to sort a large dataset efficiently, as they support fast search and insertion operations.
  7. Compact representation: Tries provide a compact representation of a large dataset, as they store only the characters that are present in the keys. This makes them an ideal data structure for storing large dictionaries or lexicons.

Tries is a tree that stores strings. The maximum number of children of a node is equal to the size of the alphabet. Trie supports search, insert and delete operations in O(L) time where L is the length of the key. 
Hashing:- In hashing, we convert the key to a small value and the value is used to index data. Hashing supports search, insert and delete operations in O(L) time on average. 

Self Balancing BST : The time complexity of the search, insert and delete operations in a self-balancing Binary Search Tree (BST) (like Red-Black Tree, AVL Tree, Splay Tree, etc) is O(L * Log n) where n is total number words and L is the length of the word. The advantage of Self-balancing BSTs is that they maintain order which makes operations like minimum, maximum, closest (floor or ceiling) and kth largest faster. Please refer Advantages of BST over Hash Table for details. 

Dynamic insertion: Tries allow for dynamic insertion of new strings into the data set.

Compression: Tries can be used to compress a data set of strings by identifying and storing only the common prefixes among the strings.

Autocomplete and spell-checking: Tries are commonly used in autocomplete and spell-checking systems.

Handling large dataset: Tries can handle large datasets as they are not dependent on the length of the strings, rather on the number of unique characters in the dataset.

Multi-language support: Tries can store strings of any language, as they are based on the characters of the strings rather than their encoding.

Why Trie? :-  

  1. With Trie, we can insert and find strings in O(L) time where L represent the length of a single word. This is obviously faster than BST. This is also faster than Hashing because of the ways it is implemented. We do not need to compute any hash function. No collision handling is required (like we do in open addressing and separate chaining)
  2. Another advantage of Trie is, we can easily print all words in alphabetical order which is not easily possible with hashing.
  3. We can efficiently do prefix search (or auto-complete) with Trie.

Issues with Trie :- 
The main disadvantage of tries is that they need a lot of memory for storing the strings. For each node we have too many node pointers(equal to number of characters of the alphabet), if space is concerned, then Ternary Search Tree can be preferred for dictionary implementations. In Ternary Search Tree, the time complexity of search operation is O(h) where h is the height of the tree. Ternary Search Trees also supports other operations supported by Trie like prefix search, alphabetical order printing, and nearest neighbor search. 
The final conclusion regarding tries data structure is that they are faster but require huge memory for storing the strings.

Applications :-

  • Tries are used to implement data structures and algorithms like dictionaries, lookup tables, matching algorithms, etc.
  • They are also used for many practical applications like auto-complete in editors and mobile applications.
  • They are used inphone book search applications where efficient searching of a large number of records is required.

Example :

C++




#include <iostream>
#include <unordered_map>
  
using namespace std;
  
const int ALPHABET_SIZE = 26;
  
// Trie node
struct TrieNode {
  unordered_map<char, TrieNode*> children;
  bool isEndOfWord;
};
  
// Function to create a new trie node
TrieNode* getNewTrieNode() {
  TrieNode* node = new TrieNode;
  node->isEndOfWord = false;
  return node;
}
  
// Function to insert a key into the trie
void insert(TrieNode*& root, const string& key) {
  if (!root) root = getNewTrieNode();
  
  TrieNode* current = root;
  for (char ch : key) {
    if (current->children.find(ch) == current->children.end())
      current->children[ch] = getNewTrieNode();
    current = current->children[ch];
  }
  current->isEndOfWord = true;
}
  
// Function to search for a key in the trie
bool search(TrieNode* root, const string& key) {
  if (!root) return false;
  
  TrieNode* current = root;
  for (char ch : key) {
    if (current->children.find(ch) == current->children.end())
      return false;
    current = current->children[ch];
  }
  return current->isEndOfWord;
}
  
int main() {
  TrieNode* root = nullptr;
  
  insert(root, "hello");
  insert(root, "world");
  insert(root, "hi");
  
  cout << search(root, "hello") << endl; // prints 1
  cout << search(root, "world") << endl; // prints 1
  cout << search(root, "hi") << endl; // prints 1
  cout << search(root, "hey") << endl; // prints 0
  
  return 0;
}


Java




import java.util.HashMap;
  
class TrieNode {
    HashMap<Character, TrieNode> children;
    boolean isEndOfWord;
    TrieNode() {
        children = new HashMap<Character, TrieNode>();
        isEndOfWord = false;
    }
}
  
class Trie {
    TrieNode root;
  
    Trie() {
        root = new TrieNode();
    }
  
    void insert(String word) {
        TrieNode current = root;
        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            if (!current.children.containsKey(ch)) {
                current.children.put(ch, new TrieNode());
            }
            current = current.children.get(ch);
        }
        current.isEndOfWord = true;
    }
  
    boolean search(String word) {
        TrieNode current = root;
        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            if (!current.children.containsKey(ch)) {
                return false;
            }
            current = current.children.get(ch);
        }
        return current.isEndOfWord;
    }
  
    public static void main(String[] args) {
        Trie trie = new Trie();
  
        trie.insert("hello");
        trie.insert("world");
        trie.insert("hi");
  
        System.out.println(trie.search("hello")); // prints true
        System.out.println(trie.search("world")); // prints true
        System.out.println(trie.search("hi")); // prints true
        System.out.println(trie.search("hey")); // prints false
    }
}


Python3




# Python equivalent
import collections
  
# Constants
ALPHABET_SIZE = 26
  
# Trie node
class TrieNode:
    def __init__(self):
        self.children = collections.defaultdict(TrieNode)
        self.is_end_of_word = False
  
# Function to create a new trie node
def get_new_trie_node():
    return TrieNode()
  
# Function to insert a key into the trie
def insert(root, key):
    current = root
    for ch in key:
        current = current.children[ch]
    current.is_end_of_word = True
  
# Function to search for a key in the trie
def search(root, key):
    current = root
    for ch in key:
        if ch not in current.children:
            return False
        current = current.children[ch]
    return current.is_end_of_word
  
if __name__ == '__main__':
    root = TrieNode()
  
    insert(root, "hello")
    insert(root, "world")
    insert(root, "hi")
  
    print(1 if search(root, "hello") else 0) # prints 1
    print(1 if search(root, "world") else 0) # prints 1
    print(1 if search(root, "hi") else 0) # prints 1
    print(1 if search(root, "hey") else 0) # prints 0
  
# This code is contributed by Vikram_Shirsat


C#




// C# equivalent
using System;
using System.Collections.Generic;
  
namespace TrieExample {
// Trie node class
class TrieNode {
    public Dictionary<char, TrieNode> Children
    {
        get;
        set;
    }
    public bool IsEndOfWord
    {
        get;
        set;
    }
    public TrieNode()
    {
        Children = new Dictionary<char, TrieNode>();
        IsEndOfWord = false;
    }
}
  
// Trie class
class Trie {
    private readonly int ALPHABET_SIZE
        = 26; // Constant for alphabet size
  
    // Function to create a new trie node
    public TrieNode GetNewTrieNode()
    {
        return new TrieNode();
    }
  
    // Function to insert a key into the trie
    public void Insert(TrieNode root, string key)
    {
        TrieNode current = root;
        foreach(char ch in key)
        {
            if (!current.Children.ContainsKey(ch)) {
                current.Children[ch] = GetNewTrieNode();
            }
            current = current.Children[ch];
        }
        current.IsEndOfWord = true;
    }
  
    // Function to search for a key in the trie
    public bool Search(TrieNode root, string key)
    {
        TrieNode current = root;
        foreach(char ch in key)
        {
            if (!current.Children.ContainsKey(ch)) {
                return false;
            }
            current = current.Children[ch];
        }
        return current.IsEndOfWord;
    }
}
  
// Main program class
class Program {
    static void Main(string[] args)
    {
        Trie trie = new Trie();
        TrieNode root = trie.GetNewTrieNode();
  
        trie.Insert(root, "hello");
        trie.Insert(root, "world");
        trie.Insert(root, "hi");
        // prints 1
        Console.WriteLine(trie.Search(root, "hello") ? 1 : 0);
        // prints 1
        Console.WriteLine(trie.Search(root, "world") ? 1 : 0);
        // prints 1
        Console.WriteLine(trie.Search(root, "hi") ? 1 : 0);
        // prints 0
        Console.WriteLine(trie.Search(root, "hey") ? 1 : 0);
    }
}
}
  
// This code is contributed by shivamsharma215


Javascript




class TrieNode {
    constructor() {
        this.children = new Map();
        this.isEndOfWord = false;
    }
}
  
class Trie {
    constructor() {
        this.root = new TrieNode();
    }
  
    insert(word) {
        let current = this.root;
        for (let i = 0; i < word.length; i++) {
            const ch = word.charAt(i);
            if (!current.children.has(ch)) {
                current.children.set(ch, new TrieNode());
            }
            current = current.children.get(ch);
        }
        current.isEndOfWord = true;
    }
  
    search(word) {
        let current = this.root;
        for (let i = 0; i < word.length; i++) {
            const ch = word.charAt(i);
            if (!current.children.has(ch)) {
                return false;
            }
            current = current.children.get(ch);
        }
        return current.isEndOfWord;
    }
}
  
const trie = new Trie();
trie.insert("hello");
trie.insert("world");
trie.insert("hi");
  
console.log(trie.search("hello")); // prints true
console.log(trie.search("world")); // prints true
console.log(trie.search("hi")); // prints true
console.log(trie.search("hey")); // prints false


Output

1
1
1
0


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 : 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
Trie Data Structure | Insert and Search
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. I
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
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
Applications, Advantages and Disadvantages of Matrix Data Structure
A matrix represents a collection of numbers arranged in an order of rows and columns. It is necessary to enclose the elements of a matrix in parentheses or brackets. For example, A matrix with 9 elements is shown below. [caption width="800"]Matrix[/caption] This Matrix [M] has 3 rows and 3 columns. Each element of matrix [M] can be referred to by i
4 min read
Applications, Advantages and Disadvantages of Hash Data Structure
Introduction : Imagine a giant library where every book is stored in a specific shelf, but instead of searching through endless rows of shelves, you have a magical map that tells you exactly which shelf your book is on. That's exactly what a Hash data structure does for your data! Hash data structures are a fundamental building block of computer sc
7 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
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
16 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