Implement a Trie -LeetCode-Amazon Interview Question

Bimala Bogati
2 min readMar 8, 2021

Find the problem description here.

Trie data structure is an efficient way of performing certain task that hash table is not as optimized for such as auto completion feature, spell checkers e.t.c.

Below, I have implemented Trie data structure that allows to insert a word, search for a word and check if a word starts with a given prefix. Find explanation in the comments !

class TrieNode{
/*
TrieNode are nodes that Trie data structure will comprise of
children is a map that holds the children of a given node
where key is one of the 26 alphabets and value is a node
a node can have 26 possible child node
endOfWord is variable that keeps track at each node
if that node is the last letter of a word
*/
public:
map<char, TrieNode*> children;
bool endOfWord;
};
class Trie {
private:
// Tree always starts with a root
TrieNode * root;

public:
Trie() {
root = new TrieNode();

}

/** Inserts a word into the trie. */
void insert(string word) {

/*you start with the root to find out where in the tree to
insert the given word */
TrieNode * current = root;

for(int i=0; i<word.length(); i++){
//if the child of the current node is NULL, create a new child
char ch = word[i];
if(current->children[ch] == NULL){
current->children[ch] = new TrieNode();
}
//go to the next node i.e child node
current = current->children[ch];

}
// the last letter will store the information
//where it says that it is end of the word
current->endOfWord = true;

}

/** Returns if the word is in the trie. */
bool search(string word) {
TrieNode * current = root;

for(int i=0; i<word.length(); i++){
char ch = word[i];
/*if the current node does not have child and we are not
finished with iterating the word, it means that
the word is not present in the trie
*/
if(current->children[ch] == NULL){
return false;
}

current = current->children[ch];
} //end for loop

/*if at this point no false value has returned then
we have the word in the trie, hence return true
true value comes from the last letter's enOfWord variable
*/
return current->endOfWord;
}

/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
TrieNode * current = root;

int len = prefix.length();
for(int i=0; i<len; i++){

char ch = prefix[i];
if(current->children[ch] == NULL){
return false;
}

current = current->children[ch];
}
return true;

}

};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/

Thank you ! Do not forget to provide feedback :)

--

--

Bimala Bogati

M-F:4pm-8pm Sat/Sun: 7a.m. — 7p.m. I teach coding for AP/undergrads reach @ bimalacal2022@gmail.com. How about we build/learn/discover/engineer sth new today?