Design Add And Search Words Data Structure Problem
Description
LeetCode Problem 211.
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 wordor false otherwise. word may contain dots '.' where dots can be matched with any letter.
Example:
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
wordDictionary.search("b.."); // return True
Constraints:
- 1 <= word.length <= 500
- word in addWord consists lower-case English letters.
- word in search consist of '.' or lower-case English letters.
- At most 50000calls will be made to addWordand search.
Solution
Approach: Trie with DFS for Dots
Store the words in a trie: each node has up to 26 children, one per letter, and the path from the root to a node spells a prefix. Each node also has an isEnd flag that marks whether an added word ends there, so "ba" does not match just because "bad" was added.
- addWord(word): start at the root and follow the child for each letter, creating missing children. Set
isEnd = trueon the last node. - search(word): walk the trie with a recursive helper
matches(node, word, i), which asks "canword[i..]be spelled starting fromnode?":- If
iis the length ofword, the whole pattern is used up: returnnode.isEnd. - If
word[i]is a letter, go to that child (returnfalseif it is missing) and continue withi + 1. - If
word[i]is'.', it can stand for any letter, so try every existing child withi + 1, and returntrueas soon as one succeeds.
- If
Without dots this is an ordinary trie lookup. A dot is what makes the search branch, and returning as soon as one branch succeeds keeps it from exploring more than needed.
Example: after adding "bad", "dad", "mad", the pattern ".ad" tries the children b, d and m at the first step. The b branch already spells "bad" to a node with isEnd = true, so the search returns true.
Complexity: addWord takes O(m) time, where m is the length of the word. search takes O(m) time for a word without dots; with dots it may visit every node of the trie in the worst case. The trie uses O(total length of all added words) space.
class TrieNode:
def __init__(self):
self.children = {} # letter -> TrieNode
self.is_end = False # True if an added word ends at this node
class WordDictionary:
def __init__(self):
self.root = TrieNode()
def addWord(self, word: str) -> None:
node = self.root
for ch in word:
if ch not in node.children:
node.children[ch] = TrieNode()
node = node.children[ch]
node.is_end = True
def search(self, word: str) -> bool:
return self._matches(self.root, word, 0)
def _matches(self, node: TrieNode, word: str, i: int) -> bool:
"""True if word[i:] spells a path from node to the end of an added word."""
if i == len(word):
return node.is_end
ch = word[i]
if ch == ".":
# A dot matches any letter: try every child.
for child in node.children.values():
if self._matches(child, word, i + 1):
return True
return False
child = node.children.get(ch)
return child is not None and self._matches(child, word, i + 1)
Now write it from memory
Close the write-up and solve it yourself against the tests.