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 :



title-img


                            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

Poisonous Plants

There are a number of plants in a garden. Each of the plants has been treated with some amount of pesticide. After each day, if any plant has more pesticide than the plant on its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each of the plants. Determine the number of days after which no plant dies, i.e. the time after which there is no plan

View Solution →

AND xor OR

Given an array of distinct elements. Let and be the smallest and the next smallest element in the interval where . . where , are the bitwise operators , and respectively. Your task is to find the maximum possible value of . Input Format First line contains integer N. Second line contains N integers, representing elements of the array A[] . Output Format Print the value

View Solution →

Waiter

You are a waiter at a party. There is a pile of numbered plates. Create an empty answers array. At each iteration, i, remove each plate from the top of the stack in order. Determine if the number on the plate is evenly divisible ith the prime number. If it is, stack it in pile Bi. Otherwise, stack it in stack Ai. Store the values Bi in from top to bottom in answers. In the next iteration, do the

View Solution →

Queue using Two Stacks

A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed. A basic que

View Solution →

Castle on the Grid

You are given a square grid with some cells open (.) and some blocked (X). Your playing piece can move along any row or column until it reaches the edge of the grid or a blocked cell. Given a grid, a start and a goal, determine the minmum number of moves to get to the goal. Function Description Complete the minimumMoves function in the editor. minimumMoves has the following parameter(s):

View Solution →

Down to Zero II

You are given Q queries. Each query consists of a single number N. You can perform any of the 2 operations N on in each move: 1: If we take 2 integers a and b where , N = a * b , then we can change N = max( a, b ) 2: Decrease the value of N by 1. Determine the minimum number of moves required to reduce the value of N to 0. Input Format The first line contains the integer Q.

View Solution →