CodingNodes / Tries / Design Add and Search Words Data Structure System design Space play · ←→ step · R restart

Problem

Build a class WordDictionary that stores words and can look them up with simple patterns:

  • WordDictionary() creates an empty dictionary.
  • addWord(word) stores word.
  • search(pattern) returns true if some stored word matches pattern letter for letter. A . in the pattern stands for any single letter.

The input is a list of calls and their arguments; the output lists what each call returns (null for the constructor and for addWord).

Constraints

  • 1 ≤ word.length ≤ 25 for addWord, and it uses only lowercase letters
  • 1 ≤ pattern.length ≤ 25 for search, made of lowercase letters and dots
  • At most 10⁴ calls in total

Examples: pick one to animate

Solutions

TimeO(L · 26^d) SpaceO(total letters)

Time: A plain letter follows one edge, but each dot may try up to 26 children, so a search with d dots visits at most 26^d branches of length L.

Space: The trie stores each letter of each added word at most once; the recursion is at most L deep.

Store the words in a trie, exactly like an ordinary prefix tree. To search, recurse on the pattern with a node and an index. A normal letter follows just that child (or fails). A dot loops over every child and succeeds if any one of them can match the rest of the pattern. At the end of the pattern, the node must be a word end.