Design Add and Search Words Data Structure
Problem Statement :
Design a data structure that supports adding new words and finding if a string matches any previously added string. Implement the WordDictionary class: WordDictionary() Initializes the object. void addWord(word) Adds word to the data structure, it can be matched later. bool search(word) Returns true if there is any string in the data structure that matches word or false otherwise. word may contain dots '.' where dots can be matched with any letter. Example: Input ["WordDictionary","addWord","addWord","addWord","search","search","search","search"] [[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]] Output [null,null,null,null,false,true,true,true] Explanation WordDictionary wordDictionary = new WordDictionary(); wordDictionary.addWord("bad"); wordDictionary.addWord("dad"); wordDictionary.addWord("mad"); wordDictionary.search("pad"); // return False wordDictionary.search("bad"); // return True wordDictionary.search(".ad"); // return True wordDictionary.search("b.."); // return True Constraints: 1 <= word.length <= 25 word in addWord consists of lowercase English letters. word in search consist of '.' or lowercase English letters. There will be at most 2 dots in word for search queries. At most 104 calls will be made to addWord and search.
Solution :
Solution in C :
typedef struct Trie {
struct Trie *children[26];
bool isWord;
} Trie;
typedef struct {
Trie *base;
} WordDictionary;
Trie* trieCreate() {
Trie *base = (Trie*) malloc(sizeof(Trie));
for (int i = 0; i < 26; i++) {
base->children[i] = NULL;
}
base->isWord = false;
return base;
}
WordDictionary* wordDictionaryCreate() {
WordDictionary *obj = malloc(sizeof(WordDictionary));
obj->base = trieCreate();
return obj;
}
void trieInsert(Trie* trie, char * word) {
int n = strlen(word);
Trie* curr = trie;
for (int i = 0; i < n; i++) {
int index = word[i]-'a';
if (curr->children[index] == NULL) {
curr->children[index] = trieCreate();
}
curr = curr->children[index];
if (i == n-1) {
curr->isWord = true;
}
}
}
void wordDictionaryAddWord(WordDictionary* obj, char * word) {
trieInsert(obj->base, word);
}
bool trieSearch(Trie* trie, char * word) {
int i, j, index, n = strlen(word);
Trie* curr = trie;
for (i = 0; i < n; i++) {
if (word[i] == '.') {
for (j = 0; j < 26; ++j) {
if (curr->children[j] != NULL) {
if (trieSearch(curr->children[j], &word[i+1])) {
return true;
}
}
}
return false;
} else {
index = word[i]-'a';
if (curr->children[index] == NULL) {
return false;
}
curr = curr->children[index];
}
}
return curr->isWord;
}
bool wordDictionarySearch(WordDictionary* obj, char * word) {
return trieSearch(obj->base, word);
}
void trieFree(Trie* obj) {
if (obj != NULL) {
for (int i=0; i < 26; ++i) {
trieFree(obj->children[i]);
}
free(obj);
}
}
void wordDictionaryFree(WordDictionary* obj) {
trieFree(obj->base);
free(obj);
}
/**
* Your WordDictionary struct will be instantiated and called as such:
* WordDictionary* obj = wordDictionaryCreate();
* wordDictionaryAddWord(obj, word);
* bool param_2 = wordDictionarySearch(obj, word);
* wordDictionaryFree(obj);
*/
Solution in C++ :
class TrieNode {
public:
TrieNode* children[26];
bool isWordCompleted;
TrieNode() {
memset(children, 0, sizeof(children));
isWordCompleted = false;
}
};
class WordDictionary {
public:
TrieNode* root;
WordDictionary() {
root = new TrieNode();
}
void addWord(string word) {
TrieNode* newRoot = root;
for (char ch : word) {
int alphabetIndex = ch - 'a';
if (newRoot -> children[alphabetIndex] == NULL) {
newRoot -> children[alphabetIndex] = new TrieNode();
}
newRoot = newRoot -> children[alphabetIndex];
}
newRoot -> isWordCompleted = true;
}
bool searchHelper(string word, int index, TrieNode* newRoot) {
if (index == word.length())
return newRoot -> isWordCompleted;
char ch = word[index];
if (ch == '.') {
for (int i = 0; i < 26; i++) {
if (newRoot -> children[i] != NULL && searchHelper(word, index + 1, newRoot -> children[i])) {
return true;
}
}
return false;
}
else {
if (newRoot -> children[ch - 'a'] == NULL) {
return false;
}
return (searchHelper(word, index + 1, newRoot -> children[ch - 'a']));
}
}
bool search(string word) {
return searchHelper(word, 0, root);
}
};
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary* obj = new WordDictionary();
* obj->addWord(word);
* bool param_2 = obj->search(word);
*/
Solution in Java :
class TrieNode {
TrieNode[] children;
boolean isWordCompleted;
TrieNode() {
children = new TrieNode[26];
isWordCompleted = false;
}
}
class WordDictionary {
TrieNode root;
WordDictionary() {
root = new TrieNode();
}
void addWord(String word) {
TrieNode newRoot = root;
for (char ch : word.toCharArray()) {
int alphabetIndex = ch - 'a';
if (newRoot.children[alphabetIndex] == null) {
newRoot.children[alphabetIndex] = new TrieNode();
}
newRoot = newRoot.children[alphabetIndex];
}
newRoot.isWordCompleted = true;
}
boolean searchHelper(String word, int index, TrieNode newRoot) {
if (index == word.length())
return newRoot.isWordCompleted;
char ch = word.charAt(index);
if (ch == '.') {
for (int i = 0; i < 26; i++) {
if (newRoot.children[i] != null && searchHelper(word, index + 1, newRoot.children[i])) {
return true;
}
}
return false;
}
else {
if (newRoot.children[ch - 'a'] == null) {
return false;
}
return searchHelper(word, index + 1, newRoot.children[ch - 'a']);
}
}
boolean search(String word) {
return searchHelper(word, 0, root);
}
}
Solution in Python :
class TrieNode:
def __init__(self):
self.children = [None] * 26
self.isWordCompleted = False
class WordDictionary:
def __init__(self):
self.root = TrieNode()
def addWord(self, word: str) -> None:
newRoot = self.root
for ch in word:
alphabetIndex = ord(ch) - ord('a')
if newRoot.children[alphabetIndex] is None:
newRoot.children[alphabetIndex] = TrieNode()
newRoot = newRoot.children[alphabetIndex]
newRoot.isWordCompleted = True
def searchHelper(self, word: str, index: int, newRoot: TrieNode) -> bool:
if index == len(word):
return newRoot.isWordCompleted
ch = word[index]
if ch == '.':
for i in range(26):
if newRoot.children[i] is not None and self.searchHelper(word, index + 1, newRoot.children[i]):
return True
return False
else:
alphabetIndex = ord(ch) - ord('a')
if newRoot.children[alphabetIndex] is None:
return False
return self.searchHelper(word, index + 1, newRoot.children[alphabetIndex])
def search(self, word: str) -> bool:
return self.searchHelper(word, 0, self.root)
View More Similar Problems
Inserting a Node Into a Sorted Doubly Linked List
Given a reference to the head of a doubly-linked list and an integer ,data , create a new DoublyLinkedListNode object having data value data and insert it at the proper location to maintain the sort. Example head refers to the list 1 <-> 2 <-> 4 - > NULL. data = 3 Return a reference to the new list: 1 <-> 2 <-> 4 - > NULL , Function Description Complete the sortedInsert function
View Solution →Reverse a doubly linked list
This challenge is part of a tutorial track by MyCodeSchool Given the pointer to the head node of a doubly linked list, reverse the order of the nodes in place. That is, change the next and prev pointers of the nodes so that the direction of the list is reversed. Return a reference to the head node of the reversed list. Note: The head node might be NULL to indicate that the list is empty.
View Solution →Tree: Preorder Traversal
Complete the preorder function in the editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's preorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the preOrder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the tree's
View Solution →Tree: Postorder Traversal
Complete the postorder function in the editor below. It received 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's postorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the postorder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the
View Solution →Tree: Inorder Traversal
In this challenge, you are required to implement inorder traversal of a tree. Complete the inorder function in your editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's inorder traversal as a single line of space-separated values. Input Format Our hidden tester code passes the root node of a binary tree to your $inOrder* func
View Solution →Tree: Height of a Binary Tree
The height of a binary tree is the number of edges between the tree's root and its furthest leaf. For example, the following binary tree is of height : image Function Description Complete the getHeight or height function in the editor. It must return the height of a binary tree as an integer. getHeight or height has the following parameter(s): root: a reference to the root of a binary
View Solution →