Skip to content

Design Add and Search Words Data Structure

MediumTrees
Decode it first. Clues, constraints, pattern and plan before any code.

Build a class WordDictionary that stores words and lets you search them with a wildcard:

  • add_word(word) (addWord in TypeScript): store word.
  • search(word): return True if some stored word matches. In the search string, a . matches any single letter; every other character must match exactly. The match has to cover the whole word, so lengths must be equal.
d = WordDictionary()
d.add_word("bad")
d.add_word("dad")
d.add_word("mad")
d.search("pad")   →  False
d.search("bad")   →  True
d.search(".ad")   →  True
d.search("b..")   →  True
d.search("b.")    →  False   (too short)

Constraints

  • 1 <= word.length <= 25
  • Words passed to add_word are lowercase English letters; search strings may also contain ..
  • There are at most 2 dots in each search query.
  • At most 10^4 calls in total.