Trie Data Structure: A blog series unlocking the secrets of Tries. From understanding the fundamentals to mastering implementations, explore real-world applications and advanced use cases
Blog
Trie data structure is an advanced data structure used for storing and searching strings efficiently. Dictionaries can be implemented efficiently using a Trie data structure and Tries are also used for the autocomplete features that we see in the search engines. Trie data structure is faster than binary search trees and hash tables for storing and retrieving data. Trie data structure is also known as a Prefix Tree or a Digital Tree. We can do prefix-based searching easily with the help of a Trie.
class TrieNode {
private TrieNode[] children;
private boolean isEndOfWord;
public TrieNode() {
this.children = new TrieNode[26]; // Assuming only lowercase English letters
this.isEndOfWord = false;
}
public TrieNode getChild(char ch) {
return children[ch - 'a'];
}
public TrieNode createChild(char ch) {
TrieNode newNode = new TrieNode();
children[ch - 'a'] = newNode;
return newNode;
}
public boolean isEndOfWord() {
return isEndOfWord;
}
public void setEndOfWord() {
isEndOfWord = true;
}
}
public class Trie {
private TrieNode root;
public Trie() {
this.root = new TrieNode();
}
public void insert(String word) {
TrieNode node = root;
for (char ch : word.toCharArray()) {
if (node.getChild(ch) == null) {
node = node.createChild(ch);
} else {
node = node.getChild(ch);
}
}
node.setEndOfWord();
}
public boolean search(String word) {
TrieNode node = searchNode(word);
return node != null && node.isEndOfWord();
}
public boolean startsWith(String prefix) {
return searchNode(prefix) != null;
}
private TrieNode searchNode(String word) {
TrieNode node = root;
for (char ch : word.toCharArray()) {
if (node.getChild(ch) == null) {
return null; // The prefix is not present in the Trie
}
node = node.getChild(ch);
}
return node;
}
public static void main(String[] args) {
Trie trie = new Trie();
trie.insert("apple");
System.out.println(trie.search("apple")); // Output: true
System.out.println(trie.search("app")); // Output: false
System.out.println(trie.startsWith("app")); // Output: true
trie.insert("app");
System.out.println(trie.search("app")); // Output: true
}
}
To learn more interesting DSA concepts, please book 1:1 free session with me where we can discuss things at length.
Copyright ©2024 Preplaced.in
Preplaced Education Private Limited
Ibblur Village, Bangalore - 560103
GSTIN- 29AAKCP9555E1ZV