MEDIUM NC#62 Blind #72 Trie / Data Structure Design

211. Design Add and Search Words Data Structure

๐Ÿ“– Problem

Design a data structure that supports adding new words and finding if a string matches any previously added word. Implement the WordDictionary class: - WordDictionary() Initializes the object. - addWord(word) Adds word to the data structure, word can consist of lowercase English letters. - search(word) Returns true if there is any word in the data structure that matches word. word may contain dots '.' where dots can match any single letter.

๐Ÿง  Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • โ€ขArray methods (`push`, `pop`, `shift`, `slice`)
  • โ€ขObject/Map/Set usage patterns
  • โ€ขFunction parameter and return typing

Logical Thinking Concepts

  • โ€ขDefine invariants before coding
  • โ€ขCheck edge cases first (`[]`, single element, duplicates)
  • โ€ขEstimate time/space before implementation

๐Ÿ’ก Approach

  • โ†’ Use Trie for efficient prefix search
  • โ†’ For wildcards, check all possible matches
  • โ†’ Insert time: O(m), Search time: O(m * 26^k) worst case
  • โ†’ Space: O(n * m) for storing words

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขUse Trie for efficient prefix search
  • โ€ขFor wildcards, check all possible matches
  • โ€ขInsert time: O(m), Search time: O(m * 26^k) worst case

Common Pitfalls

  • โ€ขSpace: O(n * m) for storing words

๐Ÿงช Test Cases

Hidden tests on submit: 4

Test Case 1
Not run
Input:
(() => { const wordDict = new WordDictionary(); return wordDict.addWord('bad'); })();
Expected:
null
Test Case 2
Not run
Input:
(() => { const wordDict = new WordDictionary(); wordDict.addWord('bad'); return wordDict.addWord('dad'); })();
Expected:
null
Test Case 3
Not run
Input:
(() => { const wordDict = new WordDictionary(); wordDict.addWord('bad'); wordDict.addWord('dad'); return wordDict.addWord('mad'); })();
Expected:
null

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit