
Problem
Solution
Submissions
Adding and Searching Words
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Design a data structure that supports adding new words and finding if a string matches any previously added string. The string may contain dots '.' where each dot can match any letter.
Example 1
- Input: ["WordDictionary", "addWord", "addWord", "addWord", "search", "search", "search", "search"]
[[], ["bad"], ["dad"], ["mad"], ["pad"], ["bad"], [".ad"], ["b.."]] - Output: [null, null, null, null, false, true, true, true]
- Explanation:
- WordDictionary wordDictionary = new WordDictionary();
- wordDictionary.addWord("bad");
- wordDictionary.addWord("dad");
- wordDictionary.addWord("mad");
- wordDictionary.search("pad"); // return false
- wordDictionary.search("bad"); // return true
- wordDictionary.search(".ad"); // return true, '.' matches any letter
- wordDictionary.search("b.."); // return true, '.' matches any letter
Example 2
- Input: ["WordDictionary", "addWord", "addWord", "search", "search", "search", "search"]
[[], ["apple"], ["banana"], ["a...."], ["apple"], ["ban"], ["b....a"]] - Output: [null, null, null, true, true, false, true]
- Explanation:
- WordDictionary wordDictionary = new WordDictionary();
- wordDictionary.addWord("apple");
- wordDictionary.addWord("banana");
- wordDictionary.search("a...."); // return true, matches "apple"
- wordDictionary.search("apple"); // return true
- wordDictionary.search("ban"); // return false
- wordDictionary.search("b....a"); // return true, matches "banana"
Constraints
- 1 ≤ word.length ≤ 25
- word consists of lowercase English letters and possibly dots '.'
- There will be at most 3 dots in word for search queries
- At most 10^4 calls will be made to AddWord and Search
- Time Complexity: O(N) for AddWord, where N is the length of the word
- Space Complexity: O(N * M) where N is the total number of characters in all words
Editorial
My Submissions
All Solutions
| Lang | Status | Date | Code |
|---|---|---|---|
| You do not have any submissions for this problem. | |||
| User | Lang | Status | Date | Code |
|---|---|---|---|---|
| No submissions found. | ||||
Solution Hints
- Consider using a Trie (Prefix Tree) data structure to efficiently store and search for words
- Each node in the Trie represents a character in a word
- For the Search operation with dots, use a recursive approach to try all possible characters at positions where dots appear
- Mark the end of words in the Trie to differentiate between prefixes and complete words
- The Trie approach is especially efficient for dictionary operations