![]() |
VOOZH | about |
Design a data structure GFGDictionary that enables to support the feature of adding new words and searching for words. The GFGDictionary class should have the following implementation:
Examples:
Input: function calls = {"GFGDictionary", "insertWord", "insertWord", "insertWord", "findWord", "findWord", "findWord", "findWord"}, strs = {{}, {"bad"}, {"dad"}, {"mad"}, {"pad"} ,{"bad"}, {".ad"}, {"b.."}}
Output: {null, null, null, null, false, true, true, true}
Explanation: Firstly, GFGDictionary constructor is called. Then "bad", "dad" and "mad" are inserted into the dictionary. So the first four values are null. Now, for the remaining findWord operations:
- Since, "pad" is not present in GFGDicitonary, therefore return false.
- Since, "bad" is present in GFGDicitonary, therefore return true.
- Since, ".ad" can be matched with "bad" and "bad" is present in GFGDicitonary, therefore return true.
- Since, "b.." can be matched with "bad" and "bad" is present in GFGDicitonary, therefore return true.
Input: function calls = {"GFGDictionary", "insertWord", "insertWord", "findWord", "findWord"}, strs = {{}, {"geek"}, {"gfg"}, {"g.g"}, {".g."}}
Output: {null, null, null, true, false}
Explanation: Firstly, GFGDictionary constructor is called. Then "geek" and "gfg" are inserted into the dictionary. So the first three values are null. Now, for the remaining findWord operations:
- Since, "g.g" can be matched with "gfg" and "gfg" is present in GFGDicitonary, therefore return true.
- Since, ".g." cannot be matched with any string in GFGDicitonary, therefore return false.
Approach: To solve the problem, follow the below idea:
To efficiently support the 'insertWord' and 'findWord' operations, implementation of Trie data structure is required. For inserting a word, we can simply insert the word in the trie. And while searching, we can start from the root of the trie and match character by character as we move down in the trie. At any point while matching, if we encounter a '.', then we need to move to all the child nodes of the current node.
Step-by-step algorithm:
Below is the implementation of the algorithm:
False True True True
Time Complexity: O(M * (26 ^ N)), where M is the number of words to be searched, and N is the length of the word.
Auxiliary Space: O(M)