Trie Data Structure in Java
Last Updated :
27 May, 2024
A Trie Data Structure is nothing but it is a tree-like data structure which is used to efficiently store and retrieve the dynamic set of Strings or Keys. It is certainly used for tasks that will involve searching for strings with common prefix like auto-complete or spell-checking applications.
In this article, we will learn about Trie Data Structure Implementation in Java.
Organization of a Trie Data Structure
In a Trie, each node represents the single character of the string. The structure of the Trie is organized such that each path from a root node to the leaf node i.e. an end of the word node, It is represent the string. The Trie data structure has an insertion operation and a searching operation. Each node may have multiple children each corresponding to a different character. A flag is usually associated with each node to mark whether the string represented by that node is completed.
Note: The root node represents an empty string.
Representation of Trie Data structure:
Explanation of the Image:
- root node is the empty node in the above tree.
- Each node represents the character, and the end-of-word nodes are the last of the tree.
- The path from the root to each end-of-word node represents the word in a Trie.
- The strings in the above Trie data structure are BOX, BALL, BAT, CAT and CHAI.
- Also, There are some word which don't make any sense but are there BALT.
Program to Implement Trie Data Structure
Below is the implementation of Trie Data Structure:
Java
// Java Program to Implement Trie
// Data Structure
// Helper Class TrieNode
class TrieNode {
TrieNode[] children;
boolean isEndOfWord;
public TrieNode() {
// Assuming lowercase English letters
children = new TrieNode[26];
isEndOfWord = false;
}
}
// Class Trie
public class Trie {
private TrieNode root;
// Constructor
public Trie() {
root = new TrieNode();
}
// Insert a word into the Trie
public void insert(String word) {
TrieNode current = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if (current.children[ch - 'a'] == null) {
current.children[ch - 'a'] = new TrieNode();
}
current = current.children[ch - 'a'];
}
current.isEndOfWord = true;
}
// Search for a word in the Trie
public boolean search(String word) {
TrieNode current = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if (current.children[ch - 'a'] == null) {
// Word not found
return false;
}
current = current.children[ch - 'a'];
}
return current != null && current.isEndOfWord;
}
// Check if a given prefix exists in the Trie
public boolean startsWith(String prefix) {
TrieNode current = root;
for (int i = 0; i < prefix.length(); i++) {
char ch = prefix.charAt(i);
if (current.children[ch - 'a'] == null) {
// Prefix not found
return false;
}
current = current.children[ch - 'a'];
}
return true;
}
// Main Method
public static void main(String[] args) {
Trie trie = new Trie();
trie.insert("hello");
trie.insert("world");
// Demonstrate search and startsWith
System.out.println(trie.search("hello"));
System.out.println(trie.search("world"));
System.out.println(trie.search("hi"));
System.out.println(trie.startsWith("hell"));
}
}
Outputtrue
true
false
true
Complexity of the Above Methods:
Operation
| Explanation
| Complexity
|
---|
Insertion (insert) Operation
| Inserting a word into Trie involves the traversing Trie from the root to leaf node corresponding to each character in word.
| - The time complexity of insertion operation is O(m).
- The space complexity of insertion operation is O(m).
|
---|
Search (search) Operation
| Searching for the word in the Trie is involve the traversing Trie from the root to leaf node corresponding to each character in word.
| - The time complexity of searching operation is O(m).
- The space complexity of searching operation is O(1).
|
---|
Prefix Search (startWith) Operation
| Checking if the given prefix exists in Trie is involve the traversing the Trie from the root to node corresponding to each character in the prefix.
| - The time complexity of Prefix Search is O(p).
- The space complexity of Prefix Search is O(1).
|
---|
Applications of Trie Data Structure:
There are some key applications of Trie data structure as mentioned below:
- Auto-Complete and Spell Checking
- Dictionary Implementations
- IP Address Lookup
- Prefix Matching
- Text Compression
- Contact Management and Search
- DNA Sequencing and Genome Analysis
- Word Frequency Counting
Conclusion
In conclusion, the Trie data structure is the powerful tool for the efficiently handling string-related operations, particularly those are involve the prefix-based searches. It is ability to the store and retrieve the strings in a hierarchical manner makes it invaluable in the wide range of the applications from the auto-complete and spell checking in the text editors to the IP routing in the computer networks and from the contact management in the mobile devices to the DNA sequencing in the bioinformatics. Trie data structure is compact the representation of common prefixes leads to the efficient storage and retrieval of the data and making it an optimal choice for scenarios involving large dictionaries or datasets.
Similar Reads
Trie Data Structure in C++ A Trie, also known as a prefix tree, is a tree-like data structure used to store a dynamic set of strings. It is particularly useful for efficient retrieval of keys in a large dataset of strings. In this article, we will explore the Trie data structure, its operations, implementation in C++, and its
8 min read
What is Data Structure? A data structure is a way of organizing and storing data in a computer so that it can be accessed and used efficiently. It refers to the logical or mathematical representation of data, as well as the implementation in a computer program.Classification:Data structures can be classified into two broad
2 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
Java Program to Implement Stack Data Structure Stack is the fundamental Data Structure that can follow the Last In, First Out(LIFO) principle. It can work that the last element added to the stack will be the first one to be removed. It can operate like a stack of plates: We can only add or remove the topmost plate at any given time. The simplici
5 min read
Triplet Class in JavaTuples A Triplet is a Tuple from JavaTuples library that deals with 3 elements. Since this Triplet is a generic class, it can hold any type of value in it. Since Triplet is a Tuple, hence it also has all the characteristics of JavaTuples:Â They are TypesafeThey are ImmutableThey are IterableThey are Serial
5 min read