noodleProblems/
Design Add and Search Words Data Structure
#142

Design Add and Search Words Data Structure

AlgorithmmediumTrieDepth First SearchStringDesign

Design a structure that stores words and supports searching for a word, where a search pattern may contain the **wildcard** . that matches **any single letter**.

The structure supports two operations:

- "addWord" — add the word word to the structure. Returns null. - "search" — return true if any stored word matches the pattern word, otherwise false. A literal letter must match that exact letter; a . matches **any one** letter. The pattern matches a stored word only if they are the **same length** and every position matches.

You are given the operations as two parallel arrays: operations[i] is the operation name and values[i] is its argument list ([word] for both operations). Apply them in order and return an array holding each operation's return value (null for every "addWord", a boolean for each "search").

For example ["addWord","addWord","addWord","search","search","search","search"] with [["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]] returns [null, null, null, false, true, true, true]. After adding "bad", "dad", "mad": search("pad") is false (no stored word); search("bad") is true; search(".ad") is true (matches all three); search("b..") is true (matches "bad").

Example cases

  • wildcards across stored words
    in operations = ["addWord","addWord","addWord","search","search","search","search"]values =
    bad
    dad
    mad
    pad
    bad
    .ad
    b..
    out [null,null,null,false,true,true,true]
    search(".ad") matches bad/dad/mad; search("b..") matches bad; search("pad") matches nothing stored.
  • length must match
    in operations = ["addWord","search","search","search"]values =
    a
    a
    .
    ..
    out [null,true,true,false]
    "." matches the single-letter "a"; ".." requires a length-2 word, and none was stored.

Constraints

  • 1 <= operations.length <= 10^4
  • operations[i] is one of "addWord", "search".
  • 1 <= word.length <= 25
  • word in addWord consists of lowercase English letters only.
  • word in search consists of lowercase English letters and the character '.'.
  • There are at most 3 dots in a search word.
Saved
operations =
["addWord","addWord","addWord","search","search","search","search"]
values =
[["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]