Design Add and Search Words Data Structure
Explore how to design and implement a WordDictionary data structure that supports adding words, searching with exact or wildcard queries, and retrieving all stored words. Understand the use of trie-like structures to efficiently manage and query words, including handling dot characters as wildcards. This lesson helps you develop a flexible solution for complex string search problems commonly asked in coding interviews.
We'll cover the following...
Statement
Design a data structure that enables the addition of new words, facilitates word search, and provides the count of all words.
Implement a struct, WordDictionary, which should provide the following functionalities:
-
NewWordDictionary(): This function will initialize the object.
-
Add Word(word): This function will store the provided word in the data structure.
-
Search Word(word): This function will return TRUE if any string in the WordDictionary object matches the query word. Otherwise, it will return FALSE.
If the query word contains dots,
., each dot is free to match any letter of the alphabet. For example, the dot in the string “.ad” can have possible search results like “aad”, “bad”, “cad”, and so on. -
Get Words(): This function will return all the words in the WordDictionary struct.
Constraints:
-
word.length -
Words passed to Add Word() consist of lowercase English letters.
-
Words passed to Search Word() consist of
.or lowercase English letters. -
There will be, at most, three dots in a word passed to Search Word().
-
At most, calls will be made to Add Word() , Get Words() and Search Word().
Examples
Understand the problem
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:
Design Add and Search Words Data Structure
Consider the list [“bin”, “pin”, “spin”, “pint”]. What will be the output of Search Word(“bin”)?
True
False
Figure it out!
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Note: The game below is only for the Add Word(word) function.
Try it yourself
Implement your solution in word_dictionary.go in the following coding playground. The supporting code template provided in dfs.go is meant to assist in developing your solution to the problem.
package maintype WordDictionary struct {// Write your code here}func NewWordDictionary() *WordDictionary {// Replace this placeholder retrun statement with your codereturn nil}func (w *WordDictionary) AddWord(word string) {// Write your code here}func (w *WordDictionary) SearchWord(word string) bool {// Replace this placeholder retrun statement with your codereturn false}func (w *WordDictionary) GetWords() []string {// Replace this placeholder retrun statement with your codereturn make([]string, 0)}