Add and Search Word
Master this topic with zero to advance depth.
Add and Search Word
Design a data structure that supports adding new words and finding if a string matches any previously added string, including wildcard character '.' matching.
Examples
Input: addWord("bad"), addWord("dad"), search(".ad")
Output: true, true, true
Approach 1
Level III: Trie + DFS (Optimal)
Intuition
Standard Trie implementation. When encountering '.', perform DFS to check all possible children of the current node.
⏱ Add: O(L), Search: O(26^L) worst case.💾 O(N * L * 26).
Detailed Dry Run
Search '.ad': Root -> dfs('.'). Try 'a'-'z'. 'b' exists. From 'b', dfs('ad') -> matches 'ad' and isEnd=true. Return true.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.