Implement Trie (Prefix Tree)
Problem Statement :
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. Example 1: Input ["Trie", "insert", "search", "search", "startsWith", "insert", "search"] [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]] Output [null, null, true, false, true, null, true] Explanation Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // return True trie.search("app"); // return False trie.startsWith("app"); // return True trie.insert("app"); trie.search("app"); // return True Constraints: 1 <= word.length, prefix.length <= 2000 word and prefix consist only of lowercase English letters. At most 3 * 104 calls in total will be made to insert, search, and startsWith.
Solution :
Solution in C :
#define N 26
typedef struct Trie{
struct Trie* children[N];
bool is_leaf;
}Trie;
Trie* trieCreate() {
Trie* node = malloc(sizeof(Trie));
for(int i = 0; i < N; i++){
node->children[i] = NULL;
}
node->is_leaf = false;
return node;
}
void trieInsert(Trie* obj, char * word) {
Trie* tmp = obj;
for(int i = 0; word[i] != '\0'; i++){
int idx = word[i] - 'a';
if(tmp->children[idx] == NULL){
tmp->children[idx] = trieCreate();
}
tmp = tmp->children[idx];
}
tmp->is_leaf = true;
}
bool trieSearch(Trie* obj, char * word) {
Trie* tmp = obj;
for(int i = 0; word[i] != '\0'; i++){
int idx = word[i] - 'a';
if(tmp->children[idx] == NULL)
return false;
tmp = tmp->children[idx];
}
return tmp->is_leaf ;
}
bool trieStartsWith(Trie* obj, char * prefix) {
Trie* tmp = obj;
for(int i = 0; prefix[i] != '\0'; i++){
int idx = prefix[i] - 'a';
if(tmp->children[idx] == NULL)
return false;
tmp = tmp->children[idx];
}
return true ;
}
void trieFree(Trie* obj) {
Trie* tmp = obj;
for(int i = 0; i < N; i++){
if(tmp->children[i] != NULL)
trieFree(tmp->children[i]);
}
free(obj);
}
Solution in C++ :
class TrieNode {
public:
TrieNode *child[26];
bool isWord;
TrieNode() {
isWord = false;
for (auto &a : child) a = nullptr;
}
};
class Trie {
TrieNode* root;
public:
Trie() {
root = new TrieNode();
}
void insert(string s) {
TrieNode *p = root;
for (auto &a : s) {
int i = a - 'a';
if (!p->child[i]) p->child[i] = new TrieNode();
p = p->child[i];
}
p->isWord = true;
}
bool search(string key, bool prefix=false) {
TrieNode *p = root;
for (auto &a : key) {
int i = a - 'a';
if (!p->child[i]) return false;
p = p->child[i];
}
if (prefix==false) return p->isWord;
return true;
}
bool startsWith(string prefix) {
return search(prefix, true);
}
};
Solution in Java :
class Trie {
Node root;
public Trie() {
root = new Node();
}
public void insert(String word) {
root.insert(word, 0);
}
public boolean search(String word) {
return root.search(word, 0);
}
public boolean startsWith(String prefix) {
return root.startsWith(prefix, 0);
}
class Node {
Node[] nodes;
boolean isEnd;
Node() {
nodes = new Node[26];
}
private void insert(String word, int idx) {
if (idx >= word.length()) return;
int i = word.charAt(idx) - 'a';
if (nodes[i] == null) {
nodes[i] = new Node();
}
if (idx == word.length()-1) nodes[i].isEnd = true;
nodes[i].insert(word, idx+1);
}
private boolean search(String word, int idx) {
if (idx >= word.length()) return false;
Node node = nodes[word.charAt(idx) - 'a'];
if (node == null) return false;
if (idx == word.length() - 1 && node.isEnd) return true;
return node.search(word, idx+1);
}
private boolean startsWith(String prefix, int idx) {
if (idx >= prefix.length()) return false;
Node node = nodes[prefix.charAt(idx) - 'a'];
if (node == null) return false;
if (idx == prefix.length() - 1) return true;
return node.startsWith(prefix, idx+1);
}
}
}
Solution in Python :
class Trie:
def __init__(self):
self.root={}
def insert(self, word: str) -> None:
cur=self.root
for letter in word:
if letter not in cur:
cur[letter]={}
cur=cur[letter]
cur['*']=''
def search(self, word: str) -> bool:
cur=self.root
for letter in word:
if letter not in cur:
return False
cur=cur[letter]
return '*' in cur
def startsWith(self, prefix: str) -> bool:
cur=self.root
for letter in prefix:
if letter not in cur:
return False
cur=cur[letter]
return True
View More Similar Problems
Delete a Node
Delete the node at a given position in a linked list and return a reference to the head node. The head is at position 0. The list may be empty after you delete the node. In that case, return a null value. Example: list=0->1->2->3 position=2 After removing the node at position 2, list'= 0->1->-3. Function Description: Complete the deleteNode function in the editor below. deleteNo
View Solution →Print in Reverse
Given a pointer to the head of a singly-linked list, print each data value from the reversed list. If the given list is empty, do not print anything. Example head* refers to the linked list with data values 1->2->3->Null Print the following: 3 2 1 Function Description: Complete the reversePrint function in the editor below. reversePrint has the following parameters: Sing
View Solution →Reverse a linked list
Given the pointer to the head node of a linked list, change the next pointers of the nodes so that their order is reversed. The head pointer given may be null meaning that the initial list is empty. Example: head references the list 1->2->3->Null. Manipulate the next pointers of each node in place and return head, now referencing the head of the list 3->2->1->Null. Function Descriptio
View Solution →Compare two linked lists
You’re given the pointer to the head nodes of two linked lists. Compare the data in the nodes of the linked lists to check if they are equal. If all data attributes are equal and the lists are the same length, return 1. Otherwise, return 0. Example: list1=1->2->3->Null list2=1->2->3->4->Null The two lists have equal data attributes for the first 3 nodes. list2 is longer, though, so the lis
View Solution →Merge two sorted linked lists
This challenge is part of a tutorial track by MyCodeSchool Given pointers to the heads of two sorted linked lists, merge them into a single, sorted linked list. Either head pointer may be null meaning that the corresponding list is empty. Example headA refers to 1 -> 3 -> 7 -> NULL headB refers to 1 -> 2 -> NULL The new list is 1 -> 1 -> 2 -> 3 -> 7 -> NULL. Function Description C
View Solution →Get Node Value
This challenge is part of a tutorial track by MyCodeSchool Given a pointer to the head of a linked list and a specific position, determine the data value at that position. Count backwards from the tail node. The tail is at postion 0, its parent is at 1 and so on. Example head refers to 3 -> 2 -> 1 -> 0 -> NULL positionFromTail = 2 Each of the data values matches its distance from the t
View Solution →