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 string.
Implement the WordDictionary class:
WordDictionary()Initializes the object.void addWord(word)Addswordto the data structure, it can be matched later.bool search(word)Returnstrueif there is any string in the data structure that matcheswordorfalseotherwise.wordmay contain dots'.'where dots can be matched with any letter.
Note: The dot character '.' acts as a wildcard that can match any single letter.
Input & Output
Example 1 — Basic Operations
$
Input:
operations = ["WordDictionary","addWord","addWord","addWord","search","search","search","search"], inputs = [[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
›
Output:
[null,null,null,null,false,true,true,true]
💡 Note:
Create dictionary, add 'bad', 'dad', 'mad'. Search 'pad' (false), 'bad' (true), '.ad' matches bad/dad/mad (true), 'b..' matches bad (true)
Example 2 — Wildcard Patterns
$
Input:
operations = ["WordDictionary","addWord","search","search","search"], inputs = [[],["a"],["."],[".."],["."]]
›
Output:
[null,null,true,false,true]
💡 Note:
Add single letter 'a'. Search '.' matches 'a' (true), '..' is length 2 but 'a' is length 1 (false), '.' matches 'a' (true)
Example 3 — Multiple Wildcards
$
Input:
operations = ["WordDictionary","addWord","addWord","search","search"], inputs = [[],["word"],["world"],["...d"],["....d"]]
›
Output:
[null,null,null,false,true]
💡 Note:
Add 'word' and 'world'. Search '...d' is length 4 but no 4-letter words end in 'd' (false), '....d' matches 'world' (true)
Constraints
- 1 ≤ word.length ≤ 25
- word consists of lowercase English letters
- At most 3 × 104 calls to addWord and search
Visualization
Tap to expand
Understanding the Visualization
1
Add Words
Store words: 'bad', 'dad', 'mad'
2
Search Pattern
Query with wildcard: '.ad'
3
Match Result
Return true (pattern matches stored words)
Key Takeaway
🎯 Key Insight: Trie structure with DFS traversal efficiently handles wildcard search by exploring all possible paths when encountering '.' characters
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code