Skip to content
Decoder

Design Add and Search Words Data Structure

Medium

Problem

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.

Example 1

d = WordDictionary()

Example 2

d.add_word("bad")

Example 3

d.add_word("dad")

Example 4

d.add_word("mad")

Example 5

Input
d.search("pad")
Output
False

Example 6

Input
d.search("bad")
Output
True

Example 7

Input
d.search(".ad")
Output
True

Example 8

Input
d.search("b..")
Output
True

Example 9

Input
d.search("b.")
Output
False
Why
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.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.