CodePark/ problems / Dictionary with Wildcard Search
START PRACTICINGPRACTICE
Coding problem · Data structures and algorithms › Tries (prefix trees)

Dictionary with Wildcard Search

mediumabout 25 minutes in an interview

Build a class PatternDictionary that stores words and checks patterns against them.

  • addWord(word) stores word. Adding the same word twice is allowed and changes nothing.
  • search(pattern) returns true if some stored word matches pattern, and false otherwise.

A word matches a pattern when they have the same length. Also, at each position, the pattern character must be either the same letter or a dot .. A dot matches exactly one letter, and it can be any letter. So ".at" matches "cat" and "bat", but not "at" or "cats".

Constraints:

  • Words are 1 to 25 lowercase English letters. Patterns are 1 to 25 characters, each a lowercase letter or ..
  • A pattern contains at most 3 dots.
  • There can be up to 20,000 calls to addWord and 20,000 calls to search, in any order. A search only sees words added before it.
Input: addWord("bat"), addWord("bad"), addWord("mad"), search("pad"), search("bad"), search(".ad"), search("b.."), search("b.") Output: undefined ×3, false, true, true, true, false"b." has two characters, and no stored word has two letters.
Input: search("..."), addWord("sun"), search("s.n"), search("..n.") Output: false, undefined, true, false