Design Add and Search Words Data Structure

MediumTries

Build a WordDictionary class that stores words and finds them, with two methods:

addWord(word) stores word. search(word) returns true if some stored word matches word, and false otherwise. In a search, a dot . matches any one letter; every other letter matches only itself, and the lengths must be equal.

Each test makes a new WordDictionary and calls its methods in order. The output lists what each call returns, with null for the constructor and for addWord.

Examples

Example 1
Input:  WordDictionary(), addWord("lamp"), addWord("lump"), search("l.mp"), search("lam"), search("...."), search(".")
Output: [null, null, null, true, false, true, false]

l.mp matches both words; lam is only the start of one; .... matches any four-letter word, and no word has one letter.

Example 2
Input:  WordDictionary(), search("."), addWord("x"), search("."), search("..")
Output: [null, false, null, true, false]

A dot needs a letter to match, so it finds nothing until x is added, and two dots never match one letter.

Constraints

  • 1 ≤ word.length ≤ 25
  • addWord gets lowercase English letters only; search gets lowercase letters and dots.
  • At most 10⁴ calls in all.

Stuck?

Hint 1

Keep the words in a trie: a tree of letters where each node marks whether a word ends there.

Hint 2

Search letter by letter. At a letter, follow that one child. At a dot, try every child of the current node with the rest of the word, and succeed if any of them does.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 9 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur