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;
struct TrieNode {
unordered_map< char , TrieNode*> children;
bool isEndOfWord;
};
TrieNode* getNewTrieNode() {
TrieNode* node = new TrieNode;
node->isEndOfWord = false ;
return node;
}
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 ;
}
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;
cout << search(root, "world" ) << endl;
cout << search(root, "hi" ) << endl;
cout << search(root, "hey" ) << endl;
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" ));
System.out.println(trie.search( "world" ));
System.out.println(trie.search( "hi" ));
System.out.println(trie.search( "hey" ));
}
}
|
Python3
import collections
ALPHABET_SIZE = 26
class TrieNode:
def __init__( self ):
self .children = collections.defaultdict(TrieNode)
self .is_end_of_word = False
def get_new_trie_node():
return TrieNode()
def insert(root, key):
current = root
for ch in key:
current = current.children[ch]
current.is_end_of_word = True
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 )
print ( 1 if search(root, "world" ) else 0 )
print ( 1 if search(root, "hi" ) else 0 )
print ( 1 if search(root, "hey" ) else 0 )
|
C#
using System;
using System.Collections.Generic;
namespace TrieExample {
class TrieNode {
public Dictionary< char , TrieNode> Children
{
get ;
set ;
}
public bool IsEndOfWord
{
get ;
set ;
}
public TrieNode()
{
Children = new Dictionary< char , TrieNode>();
IsEndOfWord = false ;
}
}
class Trie {
private readonly int ALPHABET_SIZE
= 26;
public TrieNode GetNewTrieNode()
{
return new TrieNode();
}
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 ;
}
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;
}
}
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" );
Console.WriteLine(trie.Search(root, "hello" ) ? 1 : 0);
Console.WriteLine(trie.Search(root, "world" ) ? 1 : 0);
Console.WriteLine(trie.Search(root, "hi" ) ? 1 : 0);
Console.WriteLine(trie.Search(root, "hey" ) ? 1 : 0);
}
}
}
|
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" ));
console.log(trie.search( "world" ));
console.log(trie.search( "hi" ));
console.log(trie.search( "hey" ));
|
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Like Article
Save Article