Wildcard Word Lookup with a Prefix Tree
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
Build an in-memory vocabulary index backed by a prefix tree (trie) that processes an ordered stream of insertions and pattern lookups.
Implement process_trie_operations(operations: List[str], arguments: List[List[str]]) -> List[Optional[bool]], where operations[i] and arguments[i] specify the i-th command:
"addWord"with[word]: Stores the lowercase ASCII wordword('a'–'z') in the index and appendsNoneto the output list."search"with[pattern]: Checks whether at least one word inserted by an earlier"addWord"command matchespattern, appendingTrueon a match orFalseotherwise.
Matching rules for pattern:
- Every lowercase letter (
'a'–'z') must match that identical letter at the same index. - Every period character (
'.') acts as a single-character wildcard that matches any one lowercase letter (never zero letters and never two or more letters). Consequently, a stored word can matchpatternonly iflen(word) == len(pattern).
Examples
Example 1
Input:
operations = [
"addWord", "addWord", "addWord",
"search", "search", "search", "search", "search"
]
arguments = [
["code"], ["core"], ["tare"],
["co.e"], ["c..d"], [".are"], ["cor"], ["...."]
]
Output: [None, None, None, True, False, True, False, True]
Walk-through: After storing "code", "core", and "tare", "co.e" matches "code" (and "core"), "c..d" fails because no stored word ends with 'd', ".are" matches "tare", "cor" fails because "cor" is only a prefix of "core", and "...." matches any stored 4-letter word.
Example 2
Input:
operations = ["search", "addWord", "search", "search", "addWord", "search"]
arguments = [["."], ["go"], ["."], ["g."], ["g"], ["."]]
Output: [False, None, False, True, None, True]
Walk-through: Initially the index is empty, so "." returns False. Adding "go" still leaves "." as False because '.' must match one full word of length 1, while "g." returns True. Once the 1-letter word "g" is added, "." returns True.
Constraints
1 <= len(operations) == len(arguments) <= 10^5operations[i]is"addWord"or"search".- Word and pattern lengths range from
1up to a few thousand characters (~10^3scale; optimize beyond scanning every stored word on each query, and avoid call-stack overflow on long strings). - Every
wordcontains only'a'–'z', and everypatterncontains only'a'–'z'and'.'.
Step-by-step walkthrough
Understand the operations and the wildcard rule
We need to maintain a growing dictionary of lowercase words (
'a'through'z') that supports two operations:addWord(word)insertswordinto the dictionary and producesNonein the output list.search(pattern)returnsTrueif at least one previously added word matchespattern, orFalseotherwise.
In
pattern, a lowercase letter matches only itself, while a dot.is a wildcard that matches any single letter — never zero letters and never two letters:Stored words: ["go"] search("go") -> True (exact match) search("g.") -> True ('.' matches 'o') search("g") -> False ("g" is only a prefix of "go") search(".") -> False ('.' matches 1 letter, not 2) search("...") -> False (3 dots require a 3-letter word)The entry point
process_trie_operations(operations, arguments)handles up to roughly 100,000 operations and strings up to a few thousand characters long.Why scanning a plain list of words is too slow
The simplest idea is to append every added word to a plain list, and on each
search(pattern), loop through all stored words to check whether any word has the same length and matches at every non-dot position.Why does that run out of time? Suppose we add 50,000 words of length 1,000 that all start with
"z", and then run 50,000 searches for"a..."(length 1,000). A list scan checks all 50,000 stored words on every single search — around 2.5 billion loop iterations — even though not a single word starts with'a'. We want a structure that immediately narrows down to words sharing the required prefix.Key idea: share prefixes in a Trie
A trie (also called a prefix tree) is a tree where each edge is labeled with one character, so words that begin with the same letters share the same path from the root. Because a short path can be either a complete word (
"co") or merely the start of a longer word ("code"), each node also keeps a boolean flagis_wordmarking whether a complete added word ends at that node.After adding "code", "co", "core", "tare" (* means is_word = True): (root) / \ 'c' 't' / \ (o*) (a) / \ \ 'd' 'r' 'r' / \ \ (e*) (e*) (e*)Walking a
patternfrom(root)at index0now has two simple rules:- Exact letter (
'a'–'z'): follow the single matching child edge if it exists; if there is no such edge, that path dies immediately in one step. - Wildcard (
.): try every child edge leaving the current node, advancing the pattern index by1for each child.
Once the pattern index reaches
len(pattern), we have matched the right number of characters, so we checkcurrent.is_word.- Exact letter (
Build the Trie node and `add_word`
Each
TrieNodestores a dictionarychildrenmapping a character to the nextTrieNode, plusis_word = False. Inserting a word walks down fromself.rootcharacter by character, creating a freshTrieNodewhenever a letter edge is missing, and setscurrent.is_word = Trueon the final node.class TrieNode: def __init__(self) -> None: # children: maps a single lowercase character ('a'..'z') to the next TrieNode self.children: Dict[str, "TrieNode"] = {} # True only when a complete added word ends at this exact node (not just a prefix) self.is_word: bool = False class WordDictionary: def __init__(self) -> None: self.root = TrieNode() def add_word(self, word: str) -> None: # Phase 1: Walk down from the root one character at a time, creating missing nodes. current = self.root for char in word: if char not in current.children: current.children[char] = TrieNode() current = current.children[char] # Phase 2: Mark the final node so prefixes like "app" are distinguished from "apple". current.is_word = TrueAdding a duplicate word simply walks the existing path and sets
is_word = Trueagain.Search with an explicit stack for wildcards
Because
.can branch into multiple children,searchexplores candidate paths using depth-first search (DFS). Why use an explicitstacklist instead of recursive function calls? Words and patterns can be around 1,000 characters long, and Python's default call-stack limit is 1,000 frames — so a recursive search on a 1,000-character word raisesRecursionError, whereas a list on the heap handles any length safely.Each item on
stackis a pair(current, index)meaning: "we are standing at trie nodecurrent, andpattern[index]is the next character we need to match."Pay close attention to two critical details when popping
(current, index):- When
index == len(pattern)andcurrent.is_wordisFalse, we mustcontinue(notreturn False!), because other wildcard branches may still be waiting onstack. - As soon as any branch reaches
index == len(pattern)withcurrent.is_word == True, we can immediatelyreturn Truewithout exploring the rest ofstack.
def search(self, pattern: str) -> bool: # stack: list of (trie_node, pattern_index) states still to explore via depth-first search. # Using an explicit stack avoids Python's ~1,000-frame recursion limit on long words. stack: List[Tuple[TrieNode, int]] = [(self.root, 0)] while stack: current, index = stack.pop() # Base case: we have matched every character of `pattern`. if index == len(pattern): if current.is_word: return True # Only a prefix matched here; keep checking other branches still on the stack. continue target_char = pattern[index] if target_char == ".": # Wildcard '.' matches any single letter, so branch into every existing child. for child_node in current.children.values(): stack.append((child_node, index + 1)) elif target_char in current.children: # Exact letter: follow the single matching edge if it exists. next_node = current.children[target_char] stack.append((next_node, index + 1)) return False- When
Dispatch operations and trace Example 1
The wrapper function
process_trie_operationscreates a singleWordDictionaryinstance and processes each operation in order, recordingNonefor"addWord"and the boolean result for"search".def process_trie_operations(operations: List[str], arguments: List[List[str]]) -> List[Optional[bool]]: dictionary = WordDictionary() results: List[Optional[bool]] = [] # Replay each operation in order so every search sees only earlier addWord calls. for op, args in zip(operations, arguments): if op == "addWord": dictionary.add_word(args[0]) results.append(None) elif op == "search": matched = dictionary.search(args[0]) results.append(matched) else: raise ValueError(f"Unknown operation: {op}") return resultsLet's trace Example 1 after adding
"code","core", and"tare":Trie paths: root -c-> o -d-> e (word) └ -r-> e (word) root -t-> a -r-> e (word) 1. search("co.e"): (root, 0) -'c'-> (c, 1) -'o'-> (co, 2) '.' at index 2 pushes (cod, 3) and (cor, 3) pop (cor, 3) -'e'-> (core, 4): index == 4 and is_word is True -> True 2. search("c..d"): 'c' reaches (c, 1); two dots reach (cod, 3) and (cor, 3) neither has child 'd' -> stack empties -> False 3. search(".are"): '.' at root pushes (c, 1) and (t, 1) (t, 1) matches 'a' -> 'r' -> 'e' (is_word is True) -> True 4. search("cor"): (root, 0) -'c'-> (c, 1) -'o'-> (co, 2) -'r'-> (cor, 3) index == 3, but cor.is_word is False -> stack empties -> False 5. search("...."): walks down 4 wildcard levels to reach a 4-letter word node -> TrueThe returned list is
[None, None, None, True, False, True, False, True].Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple class TrieNode: def __init__(self) -> None: # children: maps a single lowercase character ('a'..'z') to the next TrieNode self.children: Dict[str, "TrieNode"] = {} # True only when a complete added word ends at this exact node (not just a prefix) self.is_word: bool = False class WordDictionary: def __init__(self) -> None: self.root = TrieNode() def add_word(self, word: str) -> None: # Phase 1: Walk down from the root one character at a time, creating missing nodes. current = self.root for char in word: if char not in current.children: current.children[char] = TrieNode() current = current.children[char] # Phase 2: Mark the final node so prefixes like "app" are distinguished from "apple". current.is_word = True def search(self, pattern: str) -> bool: # stack: list of (trie_node, pattern_index) states still to explore via depth-first search. # Using an explicit stack avoids Python's ~1,000-frame recursion limit on long words. stack: List[Tuple[TrieNode, int]] = [(self.root, 0)] while stack: current, index = stack.pop() # Base case: we have matched every character of `pattern`. if index == len(pattern): if current.is_word: return True # Only a prefix matched here; keep checking other branches still on the stack. continue target_char = pattern[index] if target_char == ".": # Wildcard '.' matches any single letter, so branch into every existing child. for child_node in current.children.values(): stack.append((child_node, index + 1)) elif target_char in current.children: # Exact letter: follow the single matching edge if it exists. next_node = current.children[target_char] stack.append((next_node, index + 1)) return False def process_trie_operations(operations: List[str], arguments: List[List[str]]) -> List[Optional[bool]]: dictionary = WordDictionary() results: List[Optional[bool]] = [] # Replay each operation in order so every search sees only earlier addWord calls. for op, args in zip(operations, arguments): if op == "addWord": dictionary.add_word(args[0]) results.append(None) elif op == "search": matched = dictionary.search(args[0]) results.append(matched) else: raise ValueError(f"Unknown operation: {op}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Imagine organizing words in a hallway of letter-by-letter signposts: all words starting with 'c' enter the 'c' door, those continuing with 'o' take the 'o' door inside it, and a star on a room's floor marks where a real dictionary word ends. In computer science, this structure is called a trie (or prefix tree), a tree where each edge represents one character and shared prefixes share the same path from the root. When searching for a normal letter like 'c', you walk through at most one door; when you see a wildcard ., you temporarily try every door in the current room using depth-first search (DFS) — an exploration strategy that follows one branch all the way down before backing up to try the next unexplored branch.
Storing words in a flat list and comparing pattern against every word one by one is too slow at scale. If 50,000 long words start with 'z' and you search 50,000 patterns starting with 'a', a flat list re-checks all 50,000 words on every query even though none of them even match the first letter. A trie rejects "a..." in a single step at the root, and even when wildcards appear, all words sharing a prefix are explored together as a single branch rather than one word at a time.
Walk through a tiny example where we add "core" and "tare", then run search(".are") and search("cor"):
- Adding
"core"creates the pathroot -> c -> o -> r -> e*(where*meansis_word = True), and adding"tare"createsroot -> t -> a -> r -> e*. - For
search(".are"), we start with(root, 0)on our stack. At index0,.pushes both children(c_node, 1)and(t_node, 1). Popping(t_node, 1)matches'a','r', and'e'to reach(tare_node, 4). Since index4 == len(".are")andtare_node.is_wordisTrue, we immediately returnTrue. - For
search("cor"), we follow'c','o', and'r'to(cor_node, 3). Index3 == len("cor"), so we checkcor_node.is_word— it isFalse(only"core"was added, not"cor"), the stack is now empty, and we returnFalse.
Complexity
Let L be the length of the word or pattern, D be the number of . wildcards in the pattern, and N be the total number of nodes in the trie (at most 1 plus the sum of lengths of all added words).
addWordtime — O(L): We step through the L characters ofwordonce, doing an O(1) dictionary lookup (and at most one node creation) per character.searchtime without dots — O(L): Each character follows at most one dictionary edge, so at most L + 1 trie nodes are visited regardless of how many words are stored.searchtime with D dots — O(min(N, (L + 1) * 26^D)): Each trie node has a unique parent and depth, so each node at depth <= L can be popped from the stack at most once per search (giving the O(N) cap). Meanwhile, each.multiplies the number of active branches by at most 26 (the lowercase alphabet size), so at most 26^D paths walk down L + 1 levels.- Space — O(N) for the trie, plus O(L) extra space per
search: The trie stores at most one node per inserted character. Duringsearch, the DFS stack holds one active path of length at most L plus at most 25 unexplored sibling children at each level along that path, so the stack never exceeds25 * L + 1entries — unlike a breadth-first queue, which could hold up to 26^L nodes at once.
Edge cases
- Searching an empty dictionary:
root.childrenis empty, so both literal searches ("a") and wildcard searches (".") immediately empty the stack and returnFalse. - Prefix of an added word: Searching
"app"when only"apple"was added reaches the second'p'node whereis_wordisFalse, correctly returningFalse. - Both a word and its prefix added: Adding both
"cat"and"catch"setsis_word = Trueat both depth 3 and depth 5, so"cat"and"cat.."both match while"cat."returnsFalse. - Wildcard count mismatch: Because
.matches exactly one letter,"."and"..."both returnFalsewhen only"go"is stored. - Dead-end wildcard branches: When
"cxz"and"cad"are stored and we search"c.d", exploring the'x'branch fails at'd'('d'not in'x''s children) and cleanly falls back to the'a'branch still waiting on the stack. - ** ~1,000-character words and patterns:** Iterative DFS on an explicit list avoids hitting Python's ~1,000-frame call-stack recursion limit.
Common mistakes
- Forgetting to check
is_wordatindex == len(pattern): ReturningTrueas soon as the pattern runs out treats every prefix of a stored word as a full word. - Returning
Falseinside the wildcard loop or at a non-word node: Writingif not current.is_word: return False(instead ofcontinue) orreturn dfs(child, index + 1)inside the.loop aborts the entire search on the first failing branch without testing sibling branches. - Using recursion in Python on 1,000-letter inputs: A recursive helper adds one call stack frame (the runtime memory record tracking an active function call) per character and crashes with
RecursionErroraround depth 1,000. - Using
.like regex.*: Here.matches exactly one lowercase letter, never zero letters and never multiple letters.
Alternative approaches
- Group words by length in a hash map (
Dict[int, Set[str]]): Exact words without.become an O(L) set lookup! For patterns containing., you only scan stored words of the exact same length L. This is fast when few words share the same length, though it still degrades to scanning every stored word if 50,000 words all have length 10 and you run 50,000 wildcard queries of length 10. - Pre-insert all wildcard patterns on
addWord: Replacing every subset of characters inwordwith.makessearchO(L), but a word of length L generates 2^L patterns — completely infeasible once L exceeds ~15.
Follow-up questions
- How would you implement this dictionary in C++ to maximize cache locality and avoid per-node heap allocations? Keep all trie nodes inside a single
std::vector<Node>pool wherenodes[0]is the root and eachNodeholdsstd::array<int, 26> childinitialized to-1(meaning "no child"). Storing integer indices instead of rawNode*pointers avoids manualnew/deletememory management and keeps nodes contiguous in CPU cache, while an explicitstd::vector<std::pair<int, size_t>>stack prevents call-stack overflow on long strings:
#include <array>
#include <string>
#include <utility>
#include <vector>
class WordDictionary {
struct Node {
std::array<int, 26> child;
bool is_word = false;
Node() { child.fill(-1); }
};
std::vector<Node> nodes{Node()}; // nodes[0] is the root
public:
void addWord(const std::string& word) {
int cur = 0;
for (char ch : word) {
int c = ch - 'a';
if (nodes[cur].child[c] == -1) {
int next_idx = static_cast<int>(nodes.size());
nodes.emplace_back();
nodes[cur].child[c] = next_idx;
}
cur = nodes[cur].child[c];
}
nodes[cur].is_word = true;
}
bool search(const std::string& pattern) const {
std::vector<std::pair<int, size_t>> stack{{0, 0}};
while (!stack.empty()) {
auto [cur, idx] = stack.back();
stack.pop_back();
if (idx == pattern.size()) {
if (nodes[cur].is_word) return true;
continue;
}
char ch = pattern[idx];
if (ch == '.') {
for (int next_idx : nodes[cur].child) {
if (next_idx != -1) stack.push_back({next_idx, idx + 1});
}
} else if (ch >= 'a' && ch <= 'z') {
int next_idx = nodes[cur].child[ch - 'a'];
if (next_idx != -1) stack.push_back({next_idx, idx + 1});
}
}
return false;
}
};
- How can you accelerate queries dominated by
.wildcards, such as"........"? Store at each trie node (or maintain one separate trie per word length!) the remaining word lengths reachable below that node. Partitioning intotries_by_length[len(word)]is especially clean and cheap:addWord(word)inserts only into the trie forlen(word), andsearch(pattern)only searchestries_by_length[len(pattern)]. If no word of lengthlen(pattern)exists,searchreturnsFalsein O(1), and an all-dots pattern"...."immediately walks down any single valid path in O(L) steps because every leaf in that length-specific trie is guaranteed to end a word of length L! - How would you extend the data structure to support
deleteWord(word)without breaking shared prefixes? Walk down the trie alongwordwhile recording(parent_node, char, child_node)along the path; if a character is missing or the final node hasis_word == False, the word is not present so return early. Otherwise setis_word = Falseon the final node, then walk backward up the recorded path and deletechild_nodefromparent_node.childrenas long aschild_node.is_wordisFalseandchild_node.childrenis empty, stopping at the first ancestor still shared by another word.
Follow-up questions
- How would you implement this dictionary in C++ to maximize cache locality and avoid per-node heap allocations?
- How can you accelerate queries dominated by `.` wildcards, such as `"........"`?
- How would you extend the data structure to support `deleteWord(word)` without breaking shared prefixes?
Similar questions
- Running Median of an Integer Stream
- Streaming Median Tracker
- Pointer Const-Qualification and C++ Associative Maps
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses