×

Trie data structure

Trie data structure

The term “trie” comes from the word “retrieval” which means getting information. The trie data structure is a sorted extension of tree-based data structure. The trie data structure is used to store the set of strings. In the trie data structure, the address variable or pointer are same as the alphabet in each node. The trie data structure is able to find or search a word in the dictionary by the help of the prefix of given word. We can say the trie data structure is an efficient information retrieval data structure. By the help of it, we can minimize search complexities. In trie data structure, all the children are present in it have a common prefix of the string associated with that parent node and the root node of it contain the null or empty string. The trie data structure is also called the prefix tree or digital tree.

Properties of the Trie for a set of the string:

  • Trie is a tree.
  • Trie stores a set of string.
  • Trie does not contain any value at root level.
  • In trie data structure, each child of nodes is sorted in dictionary order.
  • A node in trie data structure can contain utmost 26 children ( A to Z).

Operations on Trie: -

We can perform three operation on the Trie

  • Insert a node into the trie.
  • Delete a node from the trie.
  • Search a node
  • Insert of a node in the Trie
  • For insertion a node in trie, each letter of input key is inserted as separate trie node.
  • In trie data structure, the key character or letter behaves as the index into the array children.
  • If the key which we want to input in trie data structure is not there or an extension of existing key then we will construct non-existing nodes of the key and we will mark end of word for the last node.
  • In trie data structure, the input key is prefix of already added key then we will mark the last node as end of the word.
  • The number of characters determines the depth of the trie data structure.

New node insertion implementation on Trie: -

     void insert(String word) {
         TrieNode pointer = root;
         for (char l : word.toCharArray()) {
             pointer = pointer.getNode().computeIfAbsent(l, c -> new TrieNode());
         }
         pointer.setEnding(true);
     }
     boolean delete(String word) {
         return delete(root, word, 0);
     } 
  • Searching a node in Trie

In this, we will see searching a node in a trie. The search operation is similar as the insertion operation in a trie. In search operation, we find a key in the trie. The implementation of searching operation in trie is given below.

Searching implementation on Trie: -

     boolean search(String word) {
         TrieNode pointer = root;
         for (int i = 0; i < word.length(); i++) {
             char ch = word.charAt(i);
             TrieNode node = pointer.getNode().get(ch);
             if (node == null) {
                 return false;
             }
             pointer = node;
         }
         return pointer.isEnding();
     } 
  • Deletion of a node in the Trie

Now we will be discussing how can we delete a node from the trie.

  • In the trie, if key is not there then the delete operation will be stopped.
  • In the trie, if the key is there then delete the key from the trie.

Node deletion implementation on Trie: -

     private boolean delete(TrieNode pointer, String word, int index) {
         if (index == word.length()) {
             if (!pointer.isEnding()) {
                 return false;
             }
             pointer.setEnding(false);
             return pointer.getNode().isEmpty();
         }
         char ch = word.charAt(index);
         TrieNode node = pointer.getNode().get(ch);
         if (node == null) {
             return false;
         }
         boolean check = delete(node, word, index + 1) && !node.isEnding();
         if (check) {
             pointer.getNode().remove(ch);
             return pointer.getNode().isEmpty();
         }
         return false;
     } 

Applications of Trie: -

  • Spell Checker

We can use the trie data structure as spell checker mechanism. In this, firstly it will check that word in a dictionary and it will suggest the words according to desired order. The trie data structure is efficient for searching the words into dictionary and also used to make an algorithm to include a collection of relevant words or suggestions.

  • Auto-complete

Auto-complete functionality is most popular functionality now days which used by text-editors, internet browsers and mobile applications. In this, when type or search something then it provides some suggestions based on user previous history.

Trie gives an alphabetical filter of strings entries by the key of the nodes.

  • Browser history

Trie is used to the URL or give the URL suggestion in the browser because most of browser keeps a history of URL’s of the website which the user has visited.

Advantages of Trie

  • In trie data structure, we can perform faster insert operation and search operation as compared to the hashtable and binary search tree.
  • Trie also provides an alphabetical filter of entries with the help of key of the node.

Disadvantages of Trie

  • Extra memory consumed by trie to store the strings.
  • Trie is slower as compared to hash table.

Trie implementation: -

 import java.util.HashMap;
 import java.util.Map;
 public class Triee {
     private TrieNode root;
     Triee() {
         root = new TrieNode();
     }
     class TrieNode {
     private final Map<Character, TrieNode> children = new HashMap<>();
     private boolean ending;
     Map<Character, TrieNode> getNode() {
         return children;
     }
     boolean isEnding() {
         return ending;
     }
     void setEnding(boolean ending) {
         this.ending = ending;
     }
 }
     void insert(String word) {
         TrieNode pointer = root;
         for (char l : word.toCharArray()) {
             pointer = pointer.getNode().computeIfAbsent(l, c -> new TrieNode());
         }
         pointer.setEnding(true);
     }
     boolean delete(String word) {
         return delete(root, word, 0);
     }
     boolean search(String word) {
         TrieNode pointer = root;
         for (int i = 0; i < word.length(); i++) {
             char ch = word.charAt(i);
             TrieNode node = pointer.getNode().get(ch);
             if (node == null) {
                 return false;
             }
             pointer = node;
         }
         return pointer.isEnding();
     }
     boolean isEmpty() {
         return root == null;
     }
     private boolean delete(TrieNode pointer, String word, int index) {
         if (index == word.length()) {
             if (!pointer.isEnding()) {
                 return false;
             }
             pointer.setEnding(false);
             return pointer.getNode().isEmpty();
         }
         char ch = word.charAt(index);
         TrieNode node = pointer.getNode().get(ch);
         if (node == null) {
             return false;
         }
         boolean check = delete(node, word, index + 1) && !node.isEnding();
         if (check) {
             pointer.getNode().remove(ch);
             return pointer.getNode().isEmpty();
         }
         return false;
     }
             public static void main(String[] args) {
                         boolean res;
                         Triee trie = new Triee();
                         trie.insert("art");
                         trie.insert("bunny");
                         trie.insert("buck");
                         trie.insert("dog");
                         trie.insert("Apostate");
                         res = trie.search("bunny");
                         System.out.println(res);
                         res = trie.search("duck");
                         System.out.println(res);
             }
 } 

Output: -

true

false

Time Complexity:

The time complexity of insert, search and delete are O(n), O(n), O(c*n) respectively, where n is the length of input string and c is the number of alphabets.


Related Topics

Bin Packing Problem (How to minimize the number of used Bins)

You have been given an array. The values of the array represent the size of n different items. You have been also given some bins. You have to store the...

3 minutes read.

Function to Insert a Node in a Binary Search Tree

Implementation // writing C++ code that will help us in implementing the insertion operation in a binary search tree. #include <bits/stdc++.h> using namespace std; // creating a new binary search tree node struct __nod { int...

8 minutes read.

Understanding Data Processing

Introduction Data In our everyday lives, any task that we perform online is related to data. Millions of pieces of data are produced every second across the globe. Data production is largely...

4 minutes read.

B Tree in Data Structure

Data management is called database management. A data model is a system that stores, manages, and optimizes computer resources. Data processing is not just about data storage. Almost every app...

9 minutes read.

Insertion Sort vs Bubble Sort

In this article, we will see the major differences between Insertion Sort and Bubble Sort. Before that, let’s have a quick overview of what these sorting algorithms are and what’s...

4 minutes read.

Convert Binary Tree into a Threaded Binary Tree

Implementation /*Writing a C++ program that will help us change the binary tree into a threaded binary tree and help us transform. */ #include <bits/stdc++.h> using namespace std; /*Creating the structure of a node...

11 minutes read.

Bubble Sort in Data Structures

Bubble Sort in C++ The bubble sort algorithm analyses two adjacent elements and swaps them until they are no longer in the desired order. Each iteration moves each member of the array...

4 minutes read.

Remove duplicates from an unsorted Linked List

Remove duplicates from an unsorted Linked List This article will explain how we can remove duplicates from unsorted linked lists. Here we have given an unsorted singly linked list and will...

3 minutes read.

Tree in Data Structure

Tree A tree is a non-linear data structure by which hierarchical data is displayed. As we know that there are many trees in the forest, similarly the data structure also contains...

3 minutes read.

Detect and Remove Loop in a Linked List

Create a function called detectAndRemovetheLoop() that verifies whether a given Linked List has a loop, eliminates the loop if it does, and returns true if it does. It returns false...

6 minutes read.

Heap Sort in Data Structure

Heap Sort A heap is a tree-based data structure that has specific properties. Heap is always a complete binary tree (CBT). That is, all the nodes of the tree are completely filled.If...

6 minutes read.

Binary tree deletion

This article will discuss the deletion operation's implementation in the binary tree. The deletion operation helps us eliminate an element from the tree. Implementation #include <bits/stdc++.h> using namespace std; /* A binary tree node...

4 minutes read.

Binary Tree Uses

A binary tree is a tree data structure containing hubs with at most two children for instance a right and left child. The node at the top is insinuated as the...

3 minutes read.

Linear Queue Data Structure in C

Data Structure There are many ways to store data in programming, that Queue has features that make it all the more special. We all know that data structure is a way...

9 minutes read.

Binary Tree vs Binary Search Tree: Data Structure

Difference Between Binary Tree and Binary Search Tree What is Binary Tree? A tree which each node can have utmost two children called binary tree. These children are referred as the ‘left...

3 minutes read.

Given Two Binary Trees, Check if it is Symmetric

Implementation // creating a C++ program that will help us check whether the two given trees are mirror images of each other.  #include<bits/stdc++.h> using namespace std; /* A given binary tree has a data...

5 minutes read.

Arrange consonants and vowels nodes in a linked list

Arrange consonants and vowels nodes in a linked list In this problem, we have given a singly linked list. Here we will arrange the consonants and vowels nodes of the list...

2 minutes read.

What is a Spanning Tree in Data Structure

Data structures Data management is called database management. This allows the computer to sort or organize the data for efficient retrieval. A data model is a system used to store, manage,...

5 minutes read.

Burning binary tree

Burn the Binary tree starting from the target node You have given a binary tree and a target node value. Now you have to burn the tree from target node. You...

4 minutes read.

Linear Queue VS Circular Queue

What is Queue? A queue is one of the important linear data structures extensively used in various computer applications. It is based on the FIFO (First In First Out) principle. It...

9 minutes read.