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
๐ค Output