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
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree 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. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe 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
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem