Design Add and Search Words Data Structure

Design Add and Search Words Data Structure is a Medium Data Structures and Algorithms interview problem you can solve, run and submit on Thita.ai. It belongs to the Design Patterns pattern, in the Design (General/Specific) subpattern.

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.

Topics and companies

Topics: String, Depth-First Search, Design, Trie.

Reported in interviews at Facebook, Google, Oracle, Amazon.

How to practise Design Add and Search Words Data Structure on Thita.ai

Starter code is provided in C, C#, C++, Go, Java, JavaScript and Python. Your solution runs against 5 test cases for this problem, with the AI coach available for a hint when you are stuck rather than a finished answer. The reference solution runs in O(L) for addWord and O(26^d * L) for search, where L is the length of the word and d is the number of wildcards ('.') in the search word. Since d <= 2, search is at most O(676 * L). time and O(N * L), where N is the number of words added and L is the average word length, due to the Trie structure storing all words. space.

Open Design Add and Search Words Data Structure in the code editor, or read the Design Add and Search Words Data Structure editorial for a worked solution with its approach and complexity analysis.

Where Design Add and Search Words Data Structure sits in the DSA pattern sheet

Problems related to Design Add and Search Words Data Structure

Other problems that use the same Design (General/Specific) and Design Patterns techniques:

Preparing this workspace.