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 word word ('a'–'z') in the index and appends None to the output list.
  • "search" with [pattern]: Checks whether at least one word inserted by an earlier "addWord" command matches pattern, appending True on a match or False otherwise.

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 match pattern only if len(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^5
  • operations[i] is "addWord" or "search".
  • Word and pattern lengths range from 1 up to a few thousand characters (~10^3 scale; optimize beyond scanning every stored word on each query, and avoid call-stack overflow on long strings).
  • Every word contains only 'a'–'z', and every pattern contains only 'a'–'z' and '.'.

Step-by-step walkthrough

  1. 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) inserts word into the dictionary and produces None in the output list.
    • search(pattern) returns True if at least one previously added word matches pattern, or False otherwise.

    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.

  2. 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.

  3. 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 flag is_word marking 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 pattern from (root) at index 0 now 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 by 1 for each child.

    Once the pattern index reaches len(pattern), we have matched the right number of characters, so we check current.is_word.

  4. Build the Trie node and `add_word`

    Each TrieNode stores a dictionary children mapping a character to the next TrieNode, plus is_word = False. Inserting a word walks down from self.root character by character, creating a fresh TrieNode whenever a letter edge is missing, and sets current.is_word = True on 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 = True
    

    Adding a duplicate word simply walks the existing path and sets is_word = True again.

  5. Search with an explicit stack for wildcards

    Because . can branch into multiple children, search explores candidate paths using depth-first search (DFS). Why use an explicit stack list 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 raises RecursionError, whereas a list on the heap handles any length safely.

    Each item on stack is a pair (current, index) meaning: "we are standing at trie node current, and pattern[index] is the next character we need to match."

    Pay close attention to two critical details when popping (current, index):

    1. When index == len(pattern) and current.is_word is False, we must continue (not return False!), because other wildcard branches may still be waiting on stack.
    2. As soon as any branch reaches index == len(pattern) with current.is_word == True, we can immediately return True without exploring the rest of stack.
        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
    
  6. Dispatch operations and trace Example 1

    The wrapper function process_trie_operations creates a single WordDictionary instance and processes each operation in order, recording None for "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 results
    

    Let'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 -> True
    

    The returned list is [None, None, None, True, False, True, False, True].

  7. 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"):

  1. Adding "core" creates the path root -> c -> o -> r -> e* (where * means is_word = True), and adding "tare" creates root -> t -> a -> r -> e*.
  2. For search(".are"), we start with (root, 0) on our stack. At index 0, . 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 index 4 == len(".are") and tare_node.is_word is True, we immediately return True.
  3. For search("cor"), we follow 'c', 'o', and 'r' to (cor_node, 3). Index 3 == len("cor"), so we check cor_node.is_word — it is False (only "core" was added, not "cor"), the stack is now empty, and we return False.

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).

  • addWord time — O(L): We step through the L characters of word once, doing an O(1) dictionary lookup (and at most one node creation) per character.
  • search time 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.
  • search time 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. During search, 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 exceeds 25 * L + 1 entries — unlike a breadth-first queue, which could hold up to 26^L nodes at once.

Edge cases

  • Searching an empty dictionary: root.children is empty, so both literal searches ("a") and wildcard searches (".") immediately empty the stack and return False.
  • Prefix of an added word: Searching "app" when only "apple" was added reaches the second 'p' node where is_word is False, correctly returning False.
  • Both a word and its prefix added: Adding both "cat" and "catch" sets is_word = True at both depth 3 and depth 5, so "cat" and "cat.." both match while "cat." returns False.
  • Wildcard count mismatch: Because . matches exactly one letter, "." and "..." both return False when 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_word at index == len(pattern): Returning True as soon as the pattern runs out treats every prefix of a stored word as a full word.
  • Returning False inside the wildcard loop or at a non-word node: Writing if not current.is_word: return False (instead of continue) or return 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 RecursionError around 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 in word with . makes search O(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 where nodes[0] is the root and each Node holds std::array<int, 26> child initialized to -1 (meaning "no child"). Storing integer indices instead of raw Node* pointers avoids manual new/delete memory management and keeps nodes contiguous in CPU cache, while an explicit std::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 into tries_by_length[len(word)] is especially clean and cheap: addWord(word) inserts only into the trie for len(word), and search(pattern) only searches tries_by_length[len(pattern)]. If no word of length len(pattern) exists, search returns False in 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 along word while recording (parent_node, char, child_node) along the path; if a character is missing or the final node has is_word == False, the word is not present so return early. Otherwise set is_word = False on the final node, then walk backward up the recorded path and delete child_node from parent_node.children as long as child_node.is_word is False and child_node.children is empty, stopping at the first ancestor still shared by another word.

Follow-up questions

Similar questions

More Trexquant interview questions

All 4 Trexquant questions →