Design Add and Search Words Data Structure

Medium Tries

WordDictionary() keeps a collection of words, empty to begin with.

addWord(word) adds word to the collection. Adding a word that is already in it changes nothing.

search(word) returns true when word matches some word in the collection, and false otherwise. A dot (.) in word matches any one letter and every other character matches only itself, so a match has the same length as word, with the same letter at each place that is not a dot.

Example 1

Calls:
WordDictionary()
addWord("sun")
addWord("sand")
search("s.n") → true
search("s..d") → true
search("su") → false
search(".un.") → false

s.n matches sun, its dot standing for u, and s..d matches sand. su is only the beginning of sun, and .un. has four characters, one more than sun.

Example 2

Calls:
WordDictionary()
search("a") → false
addWord("a")
search(".") → true
search("..") → false
addWord("ab")
search("..") → true
search(".b") → true

Example 3

Calls:
WordDictionary()
addWord("pear")
addWord("peak")
addWord("bear")
search("pea.") → true
search(".ear") → true
search("b.ak") → false
search("p..r") → true

Constraints

  • 1 ≤ word.length ≤ 15
  • word in addWord holds only lowercase English letters
  • word in search holds only lowercase English letters and dots, at most 4 dots
  • at most 10⁵ calls in all to addWord and search

Practice this in an AI round

30 minutes on this problem with an AI agent beside your code, then a report on your solution and how you used the agent.

See the AI round

More Tries

All Tries problems