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) Adds word to the data structure, it can be matched later.
  • bool 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.

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
Word Dictionary: Add and Search with WildcardsAdd Words• bad• dad• mad• padSearch Pattern.ad. = any letterad = exact matchMatches Found✓ bad✓ dad✓ mad✗ padResult: true (wildcard pattern found matches)
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
Asked in
Facebook 45 Google 38 Amazon 32 Microsoft 28
78.0K Views
High Frequency
~25 min Avg. Time
2.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen