A Trie is a tree-like data structure that stores strings by breaking them down into
individual characters. Each node represents a character and has
26 children
(for English
letters). The
'insert' operation
adds
characters
level by level
, creating
new nodes as needed and marking the end with a boolean. For
'search'
, we traverse
the tree checking if all characters exist and
verify the end marker
.
The
'startsWith'
operation is
similar but doesn't require the end marker.
// Make a Trie Node class TrieNode{ TrieNode[] children; boolean isEndCharacter; TrieNode(){ children = new TrieNode[26]; isEndCharacter = false; } } class Trie { TrieNode root; public Trie() { root = new TrieNode(); } public void insert(String word) { TrieNode copy = root; for(int i=0;i<word.length();i++){ char ch = word.charAt(i); // if Node doesn't exist if(copy.children[ch-'a']==null) copy.children[ch-'a'] = new TrieNode(); copy = copy.children[ch-'a']; // For the last character, make it as end. if(i==(word.length()-1)) copy.isEndCharacter = true; } } public boolean search(String word) { TrieNode copy = root; for(int i=0;i<word.length();i++){ char ch = word.charAt(i); if(copy.children[ch-'a']==null) return false; else copy = copy.children[ch-'a']; } // Whether last node field for 'isEndCharacter' is True or not. if(copy.isEndCharacter==true) return true; else return false; } public boolean startsWith(String prefix) { TrieNode copy = root; for(int i=0;i<prefix.length();i++){ char ch = prefix.charAt(i); if(copy.children[ch-'a']==null){ return false; } copy = copy.children[ch-'a']; } return true; } } /** * 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); */
Each operation (insert/search/startsWith) processes each character exactly once, where 'n'
is the
length of the input string.
Where
'm'
is
average word length and 'n'
is number of
words, as each character may require a new
node.