Design Add and Search Words Data Structure
Store words and search them with patterns where a dot stands for any letter, using a trie and DFS.
The problem
Design a class WordDictionary. addWord(word) stores a lowercase word, and search(word) returns true if some stored word matches word, where each . matches any single letter. A match needs the same length, so a . never stands for an empty spot.
Input WordDictionary(), addWord("cat"), addWord("cot"), search("c.t"), search("ca"), search("..t"), search("d..")
Output [null, null, null, true, false, true, false]
c.t matches both words, ca is only a prefix, and no word starts with d.
Input WordDictionary(), addWord("roti"), search("rot."), search("rot"), search("roti.")
Output [null, null, true, false, false]
A dot stands for exactly one letter, so the lengths must match.
Key constraint: A search has at most 2 dots and words have at most 25 letters, so branching at the dots stays cheap.
How to spot the pattern
- You look words up by exact letters plus wildcards.
- Words share prefixes, and a wildcard means trying several branches at one position.
The idea
Store the words in a trie. A normal letter in the pattern leaves only one child to follow, but a . could be any letter, so at a dot you try every child and succeed if any branch matches the rest of the pattern. That is a DFS over the trie that branches only at dots, and when the pattern runs out, the node you are on must mark the end of a word.
Brute force: Keep a list of words and compare the pattern with each one letter by letter, which costs O(number of words * L) per search.
Step by step
- 1
addWord: insert the word into a trie and mark its last node as the end of a word. - 2
search: run a DFS with a trie node and a positioniin the pattern, starting from the root and 0. - 3If
ihas reached the end of the pattern, return whether the node ends a word. - 4If the pattern has a letter at
i, move to that child, or return false if it is missing. - 5If it has a
., call the DFS on every child withi + 1and return true as soon as one call does.
Code
class TrieNode:
def __init__(self):
self.children = {} # letter -> TrieNode
self.is_word = False # True when a 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_word = True
def search(self, word: str) -> bool:
return self._match(self.root, word, 0)
def _match(self, node: TrieNode, word: str, i: int) -> bool:
# Can word[i:] be spelled from this node down to the end of a word?
if i == len(word):
return node.is_word
ch = word[i]
if ch == ".":
# a dot can be any letter, so try every child
return any(self._match(child, word, i + 1) for child in node.children.values())
child = node.children.get(ch)
return child is not None and self._match(child, word, i + 1)Complexity
Time
O(26^d * L)
Space
O(total letters)
A search with d dots branches into at most 26 children at each dot, and the rest of the walk is O(L); with at most 2 dots that is a constant factor. addWord is O(L).
Watch out for
- Returning true when the pattern ends on a node that only starts a longer word; the node must end a word.
- Giving up after the first child at a dot: if that branch fails, a later child may still match.
Follow-up questions
What if there were no limit on dots?
A pattern of all dots can visit every node at that depth, so one search could touch the whole trie. Keeping words grouped by length helps when patterns are mostly dots.
Could you do it without a trie?
Group the words by length and compare the pattern with every word of the same length. It is simpler, but slower when many words share a length.
In Hinglish
Normal letter ho toh trie mein ek hi raasta hai; dot ho toh saare children try karo. Pattern khatam hone par us node par word khatam hona zaroori hai.