Problem 444260 · medium · Level 04 Non-Linear Data Structures

Crossword Helper With Blank Squares

trie · backtracking · classes

A crossword setter keeps a word list and queries it with partly filled answers. Write the class WordDictionary:

  • add_word(word) adds word to the list (adding a word that is already there changes nothing).
  • search(pattern) returns True if some stored word fits pattern exactly, letter for letter and of the same length, where each . is a blank square that any single letter can fill.

Examples

ops:  ["WordDictionary", "add_word", "add_word", "add_word", "search", "search", "search", "search"]
args: [[], ["cot"], ["cat"], ["cog"], ["cut"], ["cog"], ["c.t"], ["c."]]
Output: [None, None, None, None, False, True, True, False]
Explanation: "c.t" matches cot and cat; "c." has the wrong length for every stored word.

Constraints

  • Words and patterns have length 1..25; words are lowercase letters; patterns are lowercase letters or .
  • Up to 10**4 calls in total
  • Target: add_word in O(len(word)); search explores only trie branches consistent with the pattern

Goals

  • Store words in a trie inside a class
  • Branch on every child when the pattern character is a wildcard
Starting Python…