Wildcard Word Dictionary Simulator
Data Structure DesignAuto-graded · 26 test casesLast updated
Simulate a word store that answers pattern queries where '.' stands for any single letter, which is best handled with a prefix tree and a depth-aware traversal.
Wildcard Word Dictionary
You are building a small word store that supports two commands:
addWord: save a word of lowercase English letters.search: given a pattern, report whether at least one saved word matches it.
A pattern is made of lowercase letters and the wildcard .. A pattern matches a word when both have the same length and, at every position, either the pattern character is . (which matches any single lowercase letter) or the two characters are identical.
Rather than a class, you write one function that replays a whole script of commands and returns the outputs.
Input
operations: a list of command names. Each is either"addWord"or"search".arguments: a list of the same length.arguments[i]is a list holding exactly one string, which is the word (foraddWord) or the pattern (forsearch) belonging tooperations[i].
Output
Return a list with one entry per command, in order:
Nonefor eachaddWordcommand.TrueorFalsefor eachsearchcommand, telling whether some word added earlier in the script matches the pattern.
If a command name is neither "addWord" nor "search", raise ValueError.
Rules and edge cases
- Only words added before a search are considered.
- Adding the same word more than once has no additional effect.
- A saved word that is merely a prefix of the pattern, or that the pattern is a prefix of, does not match, because the lengths must be equal.
- The empty string is a valid word and a valid pattern. The pattern
""matches only if the empty word was added. - A pattern made entirely of dots matches any saved word of that exact length.
- A search before any word has been added returns
False.
Constraints
- Number of commands: up to about 10^5.
- Length of each word or pattern: up to about 10^3.
- Words contain only
a-z. Patterns contain onlya-zand.. - A solution that compares the pattern against every stored word may be too slow. Aim to share work between words with common prefixes.
Examples
Example 1
Input: run_wildcard_dictionary(['addWord', 'addWord', 'addWord', 'search', 'search', 'search', 'search'], [['bad'], ['dad'], ['mad'], ['pad'], ['bad'], ['.ad'], ['b..']])
Output: [None, None, None, False, True, True, True]
Example 2
Input: run_wildcard_dictionary(['addWord', 'addWord', 'search', 'search', 'search', 'search'], [['a'], ['ab'], ['.'], ['a'], ['a.'], ['..']])
Output: [None, None, True, True, True, True]
Hints
Hint 1
Words that start the same way can share storage. Think about a prefix tree where each node knows whether a stored word ends there.
Hint 2
A normal letter in the pattern follows exactly one branch. A '.' needs to try every branch that exists at the current node.
Hint 3
Success needs two things: the whole pattern has been consumed, and the node you are standing on marks the end of a stored word. Merely existing as a path is not enough. Use an explicit stack if you want to avoid deep recursion.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Store the words in a trie. Each node has a map from letter to child node and a flag saying that a stored word ends exactly at this node.
- Adding a word: start at the root and follow or create one child per character. After the last character, set the node's flag.
- Searching a pattern: walk the trie while consuming the pattern. Keep an explicit stack of
(node, position)pairs, starting with(root, 0).- If
positionequals the pattern length, returnTruewhen the node's flag is set. Otherwise discard this entry and continue. - If the current pattern character is a letter, push the matching child if it exists.
- If it is
., push every existing child. - If the stack empties without success, return
False.
- If
An explicit stack replaces recursion, so patterns of length around 1000 cannot hit the recursion limit.
Why it is correct
- Invariant: an entry
(node, i)means the path from the root tonodespells a string of lengthithat matches the firsticharacters of the pattern, with.matching any letter. - Soundness: we answer
Trueonly wheniequals the pattern length and the node ends a stored word. That word has the pattern's length and agrees at every position. Longer or shorter words cannot be accepted, because they end at a different depth. - Completeness: if a stored word matches, then at each position its letter is either named by the pattern or covered by
.. In both cases the corresponding child is pushed. So the node where that word ends is eventually popped at the full pattern length, with its flag set. - A prefix such as
appof the stored wordappleis rejected, since its node has no end-of-word flag. - The empty pattern checks the root's flag, which is set only if the empty word was added.
Complexity
Let L be the length of a word or pattern, and let T be the total number of characters inserted.
- Add: O(L) time.
- Search with no wildcards: O(L) time.
- Search with wildcards: each node is pushed at most once, because a node at depth
donly appears with positiond. The cost is therefore bounded by the number of trie nodes at depth at mostL, which is O(T) in the worst case. This is never worse than scanning every word. - Space: O(T) for the trie, plus O(T) worst case for the search stack.
Reference solution
from typing import List, Optional
class _Node:
__slots__ = ("kids", "terminal")
def __init__(self):
self.kids = {}
self.terminal = False
def run_wildcard_dictionary(operations: List[str], arguments: List[List[str]]) -> List[Optional[bool]]:
root = _Node()
output = []
def insert(word):
cur = root
for c in word:
nxt = cur.kids.get(c)
if nxt is None:
nxt = _Node()
cur.kids[c] = nxt
cur = nxt
cur.terminal = True
def query(pattern):
n = len(pattern)
pending = [(root, 0)]
while pending:
node, pos = pending.pop()
if pos == n:
if node.terminal:
return True
continue
c = pattern[pos]
if c == '.':
for child in node.kids.values():
pending.append((child, pos + 1))
else:
child = node.kids.get(c)
if child is not None:
pending.append((child, pos + 1))
return False
for op, args in zip(operations, arguments):
if op == "addWord":
insert(args[0])
output.append(None)
elif op == "search":
output.append(query(args[0]))
else:
raise ValueError("Unsupported operation: " + str(op))
return output