Skip to main content

Introduction to Trie

What is Trie ?

A Trie, also known as a Prefix Tree, is a tree-like data structure used for efficiently storing and searching a set of strings. Each path from the root to a leaf node represents a complete word or string.

Problem Statement

We have an input array dictionary,that consists of strings. each represents a word, we have to store these strings using least space and time complexity and we can also search any string efficiently.

dictionary = ["hello","help","mom"] // insert dictionary
search("hell") -> return false // search the word "hell"
search("help") -> return true // search the word "help"

Note: Assume all letters in dictionary to be small

Insert Operation(Visual Walkthrough)

Search Operation(Visual Walkthrough)

Basic Structure of Trie

// trie class 
class Trie{
TrieNode root;// root node of trie
// function to insert the string in trie
void insert(String str){}
// function to check is string present or not
boolean search(String str){}
}

// trienode class
class TrieNode{
TrieNode[] children = new TrieNode[26];// assuming all characters are small otherwise replace 26 with 256
boolean isEnd;// to check wheteher there is any string which ends at this node
}

Implementation

class Main{
public static void main(String args[]){
Trie trie = new Trie();
// insert the dictionary
String[] dictionary = {"hello","help","mom"};
for(String word: dictionary)trie.insert(word);// insert all the word in trie
// search for the word: hell
System.out.println("is hell exist: "+trie.search("hell"));
// search for the word: help
System.out.println("is help exist: "+trie.search("help"));
}
}



// trie class
class Trie{
TrieNode root;// root node of trie
// constructor
Trie(){
root = new TrieNode();
}
// function to insert the string in trie
void insert(String str){
TrieNode start = root;
// loop through string
for(int i=0;i<str.length();i++){
char c = str.charAt(i);// character
if(start.letters[c-'a']==null){
// means character is missing so include it
start.letters[c-'a'] = new TrieNode();
}
start = start.letters[c-'a'];// move to next node
}
start.isEnd = true;// we reach to the last node so mark it true
}
// function to check is string present or not
boolean search(String str){
TrieNode start = root;
// loop through string
for(int i=0;i<str.length();i++){
char c = str.charAt(i);// character
if(start.letters[c-'a']==null)return false;
start = start.letters[c-'a'];// move to next node
}
return start.isEnd;
}
}

// trienode class
class TrieNode{
TrieNode[] letters = new TrieNode[26];// assuming all characters are small otherwise replace 26 with 256
boolean isEnd;// to check wheteher there is any string which ends at this node
// constructor
TrieNode(){
for(int i=0;i<26;i++)letters[i] = null;
isEnd = false;
}
}

Time complexity for inserting all words

O(N*L) where N is length of the dictionary and L is average length of words

Time complexity for searching a word

O(L) where L is average length of words