*https://hackernoon.com/14-patterns-to-ace-any-coding-interview-question-c5bb3357f6ed*
→ https://www.youtube.com/watch?v=Dq_ObZwTY_Q&ab_channel=AlgoMonster — Good explain!
A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.
Implement the Trie class:
Trie()
Initializes the trie object.void insert(String word)
Inserts the string word
into the trie.boolean search(String word)
Returns true
if the string word
is in the trie (i.e., was inserted before), and false
otherwise.boolean startsWith(String prefix)
Returns true
if there is a previously inserted string word
that has the prefix prefix
, and false
otherwise.class Trie {
private TrieNode root;
private class TrieNode {
boolean isEndOfWord;
Map<Character, TrieNode> children;
// Constructor
public TrieNode() {
this.isEndOfWord = false;
this.children = new HashMap<>();
}
}
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
TrieNode trieNode = root;
// Insert a word into the Trie
for (char c : word.toCharArray()) {
// If the character is not already in the children of the current TrieNode
// add it with a new TrieNode
trieNode.children.putIfAbsent(c, new TrieNode());
trieNode = trieNode.children.get(c);
}
trieNode.isEndOfWord = true;
// System.out.println("~> trie");
// System.out.println(trieNode.isEndOfWord);
// System.out.println(trieNode.children);
// System.out.println(root.children.get('a').children.get('p').children.get('p').children);
}
private TrieNode getNode(String word) {
TrieNode trieNode = root;
for (char c : word.toCharArray()) {
// Return false on not found
if (!trieNode.children.containsKey(c)) return null;
// Else we just traverse
trieNode = trieNode.children.get(c);
}
return trieNode;
}
public boolean search(String word) {
TrieNode n = getNode(word);
return (n != null) && n.isEndOfWord;
}
public boolean startsWith(String prefix) {
TrieNode n = getNode(prefix);
return n != null;
}
}
/**
* Your Trie object will be instantiated and called as such:
* Trie obj = new Trie();
* obj.insert(word);
* boolean param_2 = obj.search(word);
* boolean param_3 = obj.startsWith(prefix);
*/