Skip to content
Related Articles
Open in App
Not now

Related Articles

Advantages of Trie Data Structure

Improve Article
Save Article
  • Difficulty Level : Easy
Improve Article
Save Article

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.

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


Output

1
1
1
0

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!