Advantages of Trie Data Structure
Last Updated :
29 Mar, 2024
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 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.
- 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.
- Auto-complete: Tries are widely used in applications that require auto-complete functionality, such as search engines or predictive text input.
- 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.
- Efficient sorting: Tries can be used to sort a large dataset efficiently, as they support fast search and insertion operations.
- 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? :-
- 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)
- Another advantage of Trie is, we can easily print all words in alphabetical order which is not easily possible with hashing.
- 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
Similar Reads
Applications of tree data structure
A tree is a type of data structure that represents a hierarchical relationship between data elements, called nodes. The top node in the tree is called the root, and the elements below the root are called child nodes. Each child node may have one or more child nodes of its own, forming a branching st
4 min read
Advanced Data Structures
Advanced Data Structures refer to complex and specialized arrangements of data that enable efficient storage, retrieval, and manipulation of information in computer science and programming. These structures go beyond basic data types like arrays and lists, offering sophisticated ways to organize and
2 min read
Trie Data Structure
The Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Types of Heap Data Structure
Different types of heap data structures include fundamental types like min heap and max heap, binary heap and many more. In this post, we will look into their characteristics, and their use cases. Understanding the characteristics and use cases of these heap data structures helps in choosing the mos
8 min read
Binary Tree Data Structure
A Binary Tree Data Structure is a hierarchical data structure in which each node has at most two children, referred to as the left child and the right child. It is commonly used in computer science for efficient storage and retrieval of data, with various operations such as insertion, deletion, and
3 min read
Tree Data Structure
Tree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes.Basics of Tree Data StructureIntroduction to TreeTypes of Trees in Data StructuresApplications of tr
4 min read
Advantages of Distributed database
Distributed databases basically provide us the advantages of distributed computing to the database management domain. Basically, we can define a Distributed database as a collection of multiple interrelated databases distributed over a computer network and a distributed database management system as
4 min read
Advantages and Disadvantages of Tree
Tree is a non-linear data structure. It consists of nodes and edges. A tree represents data in a hierarchical organization. It is a special type of connected graph without any cycle or circuit.Advantages of Tree:Efficient searching: Trees are particularly efficient for searching and retrieving data.
2 min read
Types of Trees in Data Structures
A tree in data structures is a hierarchical data structure that consists of nodes connected by edges. It is used to represent relationships between elements, where each node holds data and is connected to other nodes in a parent-child relationship.Types of Trees TreeThe main types of trees in data s
4 min read
Hash Table Data Structure
What is Hash Table?A Hash table is defined as a data structure used to insert, look up, and remove key-value pairs quickly. It operates on the hashing concept, where each key is translated by a hash function into a distinct index in an array. The index functions as a storage location for the matchin
11 min read