Design Add and Search Words Data Structure

Medium#211search with .

Build a class with two methods: addWord(word) stores a word, and search(word) says whether some stored word fits it, where a "." in the search stands for any one letter. Our calls: addWord("pot"), addWord("pin"), search("p.t") — the search returns true, because "pot" fits.

input
Calls one after another: WordDictionary() makes an empty dictionary, then addWord(word) and search(word) in any order. In search, a dot . stands for any one letter.
returns
search(word): whether an added word matches word, letter for letter, a dot matching any letter. addWord returns nothing (null in the output).
constraints
  • 2 ≤ calls ≤ 2000
  • 1 ≤ word.length ≤ 25
  • addWord: lowercase English letters; search: those and dots, at most 2
our 8 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
var WordDictionary = function() {

};

/**
 * @param {string} word
 * @return {void}
 */
WordDictionary.prototype.addWord = function(word) {

};

/**
 * @param {string} word
 * @return {boolean}
 */
WordDictionary.prototype.search = function(word) {

};

/**
 * Your WordDictionary object will be instantiated and called as such:
 * var obj = new WordDictionary()
 * obj.addWord(word)
 * var param_2 = obj.search(word)
 */
Ctrl ↵
format
reset

saved in this browser

8 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more trie (prefix tree) problems

Pattern “Trie (prefix tree)” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.