Python coding

Dictionary with wildcard lookups

Write a class WildcardDictionary that stores words and answers pattern lookups.

  • add(word) stores word.
  • match(pattern) returns True if some stored word has the same length as pattern and agrees with it at every position, where a . in the pattern stands for any single letter; otherwise it returns False.

Words use lowercase a–z; words and patterns have 1 to 20 characters, and the same word may be added more than once.

The tests call the provided run_dictionary(ops): it applies each operation in order and returns the list of results (None for add, shown as null).

  • run_dictionary([["add","cat"],["add","cot"],["match","cat"],["match","c.t"],["match","cut"],["match","c.."],["match","ca"]]) → [null,null,true,true,false,true,false]
  • run_dictionary([["match","a"],["add","a"],["match","a"],["match","."],["match",".."]]) → [false,null,true,true,false]
  • run_dictionary([["add","cart"],["match","car"],["match","car."],["match","cart."],["match","...."]]) → [null,false,true,false,true]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Store the words in a trie with an end mark. A pattern without dots is a plain lookup: follow one child per letter, and the last node must carry the end mark.

Hint 2

A . has no single child to follow, so branch: try every child of the current node with the rest of the pattern, recursively, and succeed if any branch does.

Hint 3

Return True only when the pattern runs out exactly on an end mark. And don't return the first child's result: a child that fails must fall through to its siblings.

Solution and why it works
pythonadd O(L); match O(L) without dots, up to O(26^d · L) with d dots, L = length · O(total letters stored)
# --- your code ---
class WildcardDictionary:
    def __init__(self) -> None:
        self.root = {}                   # node = {letter: child}; "$" marks the end of a word

    def add(self, word: str) -> None:
        node = self.root
        for ch in word:
            node = node.setdefault(ch, {})
        node["$"] = True

    def match(self, pattern: str) -> bool:
        def dfs(node: dict, i: int) -> bool:
            if i == len(pattern):
                return "$" in node       # a prefix alone is not a word
            ch = pattern[i]
            if ch == ".":                # wildcard: any child may continue the match
                return any(dfs(kid, i + 1) for key, kid in node.items() if key != "$")
            return ch in node and dfs(node[ch], i + 1)

        return dfs(self.root, 0)


# --- provided: do not edit ---
def run_dictionary(ops: list[list]) -> list:
    words = WildcardDictionary()
    return [getattr(words, name)(*args) for name, *args in ops]

The trie turns a lookup into a walk: a letter follows one child, while a . cannot choose, so it tries every child with the rest of the pattern (a small DFS). A pattern with no dots costs O(length); each dot multiplies the work by at most 26. Traps: ending on a node without an end mark is only a prefix ("car" when only "cart" was added), and returning the first child's result instead of any misses matches in sibling branches.