Design Add and Search Words Data Structure

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

Design a data structure that supports adding new words and finding if a string matches any previously added string.

Implement the WordDictionary class:

  • WordDictionary() — Initializes the object.
  • addWord(word) — Adds word to the data structure. It can be matched later.
  • search(word) — Returns true if there is any string in the data structure that matches word, or false otherwise. word may contain dots '.' where dots can be matched with any letter.

Examples

Example 1:

Input: operations = ["WordDictionary","addWord","addWord","addWord","search","search","search","search"], operands = [[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]

Output: [null,null,null,null,false,true,true,true]

Explanation: The WordDictionary is initialized, then "bad", "dad", and "mad" are added. Searching for "pad" returns false (not added). Searching for "bad" returns true (exact match). Searching for ".ad" returns true (matches "bad", "dad", or "mad"). Searching for "b.." returns true (matches "bad").

Example 2:

Input: operations = ["WordDictionary","addWord","addWord","search","search","search"], operands = [[],["at"],["and"],["a"],["a."],["a.d"]]

Output: [null,null,null,false,true,true]

Explanation: After adding "at" and "and", searching "a" returns false (no exact match). Searching "a." returns true (matches "at"). Searching "a.d" returns true (matches "and").

Constraints

  • 1 <= word.length <= 25
  • word in addWord consists of lowercase English letters
  • word in search consists of lowercase English letters or '.'
  • At most 10⁴ calls will be made to addWord and search
Source: Trie pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle