{"id":"design-add-and-search-words-data-structure","title":"Design Add and Search Words Data Structure","difficulty":"medium","patterns":["trie"],"primaryConcept":"trie-basics","concepts":["trie-basics"],"problemForm":"core","companies":["Amazon","Google","Meta","Microsoft","Apple"],"category":"trees-graphs","executionStyle":"ops-class","compareMode":"exact","syntheticTestConfig":{"inputShape":"operations","primaryParam":"operations","sizeMetric":"op-count-plus-word-lengths","opVocabulary":[{"name":"WordDictionary","arity":0,"weight":1},{"name":"addWord","arity":1,"argTypes":["string"],"weight":3},{"name":"search","arity":1,"argTypes":["string"],"weight":4}],"secondaryParam":"arguments"},"description":"Design a `WordDictionary` that supports adding words and searching words.\n\nImplement:\n- `addWord(word)` to store `word`\n- `search(word)` to return whether any stored word matches `word`\n\nThe search pattern may contain `.` characters. A `.` matches any single lowercase letter.","examples":[{"input":"dict = WordDictionary()\ndict.addWord(\"bad\")\ndict.addWord(\"dad\")\ndict.addWord(\"mad\")\ndict.search(\"pad\")\ndict.search(\"bad\")\ndict.search(\".ad\")\ndict.search(\"b..\")","output":"[null, null, null, null, false, true, true, true]","explanation":"\".ad\" matches any stored three-letter word ending in \"ad\", and \"b..\" matches \"bad\"."},{"input":"dict = WordDictionary()\ndict.addWord(\"a\")\ndict.search(\".\")\ndict.search(\"..\")","output":"[null, null, true, false]","explanation":"The wildcard matches exactly one character, so \"..\" cannot match a one-letter word."}],"constraints":[{"id":"1-len-word-25","text":"1 <= len(word) <= 25"},{"id":"word-in-addword-consists-of-lowercase-english-letters","text":"word in addWord consists of lowercase English letters"},{"id":"word-in-search-consists-of-lowercase-english-letters-or","text":"word in search consists of lowercase English letters or '.'"},{"id":"at-most-10000-calls-will-be-made-to-addword-and-search","text":"At most 10000 calls will be made to addWord and search"}],"starterCode":"class TrieNode:\n    def __init__(self):\n        self.children = {}\n        self.is_end = False\n\nclass WordDictionary:\n    def __init__(self):\n        # Your code here\n        pass\n\n    def addWord(self, word: str) -> None:\n        # Your code here\n        pass\n\n    def search(self, word: str) -> bool:\n        # Your code here\n        pass","functionName":"WordDictionary","testCases":[{"id":"1","input":{"operations":["WordDictionary","addWord","addWord","addWord","search","search","search","search"],"arguments":[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]},"expected":[null,null,null,null,false,true,true,true],"description":"Canonical wildcard trie example."},{"id":"2","input":{"operations":["WordDictionary","addWord","search","search","search","search"],"arguments":[[],["a"],["."],["a"],["b"],[".."]]},"expected":[null,null,true,true,false,false],"description":"Single-character word and wildcard length check."},{"id":"3","input":{"operations":["WordDictionary","addWord","addWord","addWord","addWord","search","search","search","search","search"],"arguments":[[],["at"],["and"],["an"],["add"],["a"],[".at"],["an."],["a.d"],["b."]]},"expected":[null,null,null,null,null,false,false,true,true,false],"description":"Shared prefixes with wildcard branching."},{"id":"4","input":{"operations":["WordDictionary","addWord","addWord","addWord","search","search","search","search"],"arguments":[[],["ran"],["rune"],["runner"],["ru.e"],["run.."],["r.n"],["....er"]]},"expected":[null,null,null,null,true,false,true,true],"description":"Wildcard searches must still match exact pattern length."},{"id":"h1","input":{"operations":["WordDictionary","addWord","search","search","search"],"arguments":[[],["abc"],["abc"],["ab."],["a.c"]]},"expected":[null,null,true,true,true]},{"id":"h2","input":{"operations":["WordDictionary","addWord","addWord","search","search","search","search"],"arguments":[[],["bad"],["baddy"],["ba."],["ba.."],["b...."],["b....."]]},"expected":[null,null,null,true,false,true,false]},{"id":"h3","input":{"operations":["WordDictionary","addWord","addWord","addWord","search","search","search","search"],"arguments":[[],["a"],["ab"],["abc"],["."],[".."],["..."],["...."]]},"expected":[null,null,null,null,true,true,true,false]},{"id":"h4","input":{"operations":["WordDictionary","addWord","addWord","search","search","search","search"],"arguments":[[],["ran"],["runner"],["r.n"],["ru..er"],["r...."],["r.nner"]]},"expected":[null,null,null,true,true,false,true]},{"id":"h5","input":{"operations":["WordDictionary","addWord","addWord","addWord","search","search","search"],"arguments":[[],["x"],["xy"],["xyz"],["x.."],[".y."],["z.."]]},"expected":[null,null,null,null,true,true,false]},{"id":"h6","input":{"operations":["WordDictionary","addWord","addWord","search","search","search","search"],"arguments":[[],["cat"],["dog"],["c.t"],["d.g"],["c.g"],["...."]]},"expected":[null,null,null,true,true,false,false]},{"id":"topup-1","input":{"operations":["WordDictionary","addWord","addWord","addWord","search","search","search","search"],"arguments":[[],["can"],["cap"],["cape"],["ca."],["c..e"],[".ap"],["...."]]},"expected":[null,null,null,null,true,true,true,true],"description":"Top-up case 1: shared prefixes require wildcard traversal without losing exact word lengths."},{"id":"topup-2","input":{"operations":["WordDictionary","search","addWord","search","search","addWord","search","search"],"arguments":[[],["."],["a"],["."],[".."],["ab"],["a."],["ab."]]},"expected":[null,false,null,true,false,null,true,false],"description":"Top-up case 2: searches before insertion and after adding a longer word keep length checks strict."}],"hints":[{"level":1,"content":"Store words in a trie so a normal character can follow one child edge."},{"level":2,"content":"When search sees '.', try every child from the current trie node."},{"level":3,"content":"Use a recursive helper with the pattern index and current trie node. At the end of the pattern, `return` the node's terminal marker."}],"guidedFlow":{"version":2,"progressRevision":"design-add-search-2026-07-19-derivation","approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"scan-all-words","name":"Scan every stored word","summary":"Keep all words in a list and compare every word against the pattern.","decisionReason":"A pattern like b.. must compare against every stored word of length 3, even though the first letter rules out most words. As the dictionary grows, each search repeats prefix checks the trie already organizes.","complexity":{"time":"O(n*m) per search","space":"O(T)"},"tradeoffs":["Runs in O(n*m) per search time and uses O(T) space."],"isOptimal":false},{"id":"trie-dfs","name":"Trie with recursive wildcard search","summary":"Index stored words by their next character so a search advances one pattern position at a time.","decisionReason":"Each addWord path stores one character per trie level. A search reaches the child choices for its current stored prefix instead of restarting against every complete word.","complexity":{"time":"O(m) insert, O(26^d * m) worst-case search","space":"O(T)"},"tradeoffs":["Runs in O(m) insert, O(26^d * m) worst-case search time and uses O(T) space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"node-class","title":"Create trie nodes","description":"Give each trie node child storage and a terminal marker.","commonMistakes":["Missing the terminal marker","Sharing one child map across all nodes"],"hint":"Every node needs its own child map and an is-word flag.","semanticSpec":{"intent":"Initialize reusable trie node state.","doneWhen":"A trie node initializes child-link storage and terminal word state.","shouldFailWhen":"This step should fail if nodes cannot store child edges or word endings.","roles":["trie node","children","terminal marker"],"mustProve":["Each node owns child-link state.","Each node owns terminal word state."],"mustNotAccept":["A node that stores only children and no terminal marker."],"proofSnippets":[{"id":"py-word-dictionary-node-class","language":"python","code":"class TrieNode:\n    def __init__(self):\n        child_store = {}\n        self.children = child_store\n        self.is_end = False"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"initializes_trie_node_state","scope":"node-class","readMode":"tree-trie-value-query-v1"}]}},{"id":"trie-root","title":"Initialize the root","description":"Create one shared root node for all inserted words and searches.","commonMistakes":["Creating a new root inside each method","Leaving root uninitialized"],"hint":"The dictionary object should keep one persistent root.","semanticSpec":{"intent":"Initialize the persistent trie root.","doneWhen":"The WordDictionary constructor stores a root trie node.","shouldFailWhen":"This step should fail if root state is missing or local to a method.","roles":["dictionary object","root trie node"],"mustProve":["The root node is persistent instance state."],"mustNotAccept":["A root variable created only inside addWord or search."],"proofSnippets":[{"id":"py-word-dictionary-trie-root","language":"python","code":"class TrieNode:\n    def __init__(self):\n        child_store = {}\n        self.children = child_store\n        self.is_end = False\n\nclass WordDictionary:\n    def __init__(self):\n        self.root = TrieNode()"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"initializes_trie_root","scope":"trie-class","readMode":"tree-trie-value-query-v1"}]}},{"id":"add-word","title":"Insert words","description":"Walk the trie, create missing child nodes, and mark the final node as a complete word.","commonMistakes":["Not creating missing child nodes","Forgetting to mark the final node"],"hint":"Insertion is the standard trie path walk followed by a terminal marker write.","semanticSpec":{"intent":"Insert a word into the trie.","doneWhen":"addWord walks or creates one child edge per character and writes the terminal marker at the end.","shouldFailWhen":"This step should fail if words are stored only in a list or the terminal marker is never written.","roles":["word","trie path","terminal marker"],"mustProve":["The path walk creates missing trie nodes.","The final node is marked as a complete word."],"mustNotAccept":["Only storing the raw word outside the trie."],"proofSnippets":[{"id":"py-word-dictionary-add-word","language":"python","code":"class TrieNode:\n    def __init__(self):\n        self.children = {}\n        self.is_end = False\n\nclass WordDictionary:\n    def __init__(self):\n        self.root = TrieNode()\n\n    def addWord(self, word: str) -> None:\n        node = self.root\n        for char in word:\n            if char not in node.children:\n                node.children[char] = TrieNode()\n            node = node.children[char]\n        node.is_end = True"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"inserts_trie_word","scope":"insert-method","readMode":"tree-trie-value-query-v1"}]}},{"id":"wildcard-search","title":"Return wildcard search result","description":"DFS through the trie, following exact characters directly and branching over all children for ., then return whether the pattern reaches a terminal word.","commonMistakes":["Treating '.' as a literal child key","Returning true before checking the terminal marker","Advancing to only one child for a wildcard"],"hint":"The recursive state is the pattern index plus the current trie node; the public search returns the DFS result.","semanticSpec":{"intent":"Implement trie DFS search with wildcard branch expansion.","doneWhen":"search starts from the root, returns the terminal marker at the end of the pattern, recursively tries all children for ., follows indexed child links for normal characters, and returns the DFS result.","shouldFailWhen":"This step should fail if wildcard search does not recursively branch over child nodes.","roles":["pattern index","current trie node","wildcard branch"],"mustProve":["The recursive base case returns the current node's terminal marker.","A wildcard loops over child links and recurses into each child.","A normal character recurses into the indexed child link."],"mustNotAccept":["Checking only exact characters.","Scanning all stored words outside the trie."],"proofSnippets":[{"id":"py-word-dictionary-wildcard-search","language":"python","code":"class TrieNode:\n    def __init__(self):\n        self.children = {}\n        self.is_end = False\n\nclass WordDictionary:\n    def __init__(self):\n        self.root = TrieNode()\n\n    def addWord(self, word: str) -> None:\n        node = self.root\n        for char in word:\n            if char not in node.children:\n                node.children[char] = TrieNode()\n            node = node.children[char]\n        node.is_end = True\n\n    def search(self, word: str) -> bool:\n        def dfs(index: int, node: TrieNode) -> bool:\n            if index == len(word):\n                return node.is_end\n            char = word[index]\n            if char == '.':\n                for child in node.children.values():\n                    if dfs(index + 1, child):\n                        return True\n                return False\n            if char not in node.children:\n                return False\n            return dfs(index + 1, node.children[char])\n\n        return dfs(0, self.root)"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"searches_wildcard_trie_word","scope":"wildcard-search","readMode":"tree-trie-value-query-v1"}]}}],"slides":[{"id":"opener","kind":"info","chapter":"The problem","eyebrow":"Read the problem","title":"Store words, then search them with a wildcard","workspacePanel":"problem","body":["You are building a small dictionary of lowercase words. addWord(word) remembers a word. search(pattern) returns true when some stored word matches the pattern, where a \".\" in the pattern matches any single letter.","Add \"bad\", \"dad\", and \"mad\", then ask search(\"bad\") and you get true, because \"bad\" was stored. Ask search(\"pad\") and you get false, because no stored word is \"pad\". Ask search(\".ad\") and you get true, because \"bad\", \"dad\", and \"mad\" all end in \"ad\", so the wildcard can stand for any of b, d, or m. That wildcard, which fits more than one stored word at once, is what makes the search interesting."]},{"id":"brute-force","kind":"code-trace","chapter":"The slow way","eyebrow":"The obvious way","title":"Keep every word in a flat list","summary":"Comparing the pattern against every stored word answers each search correctly, but it re-reads all of them every time. Watch how much each search walks before it can decide.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def search(words: list[str], pattern: str) -> bool:\n    def matches(word: str) -> bool:\n        if len(word) != len(pattern):\n            return False\n        for index in range(len(word)):\n            expected = pattern[index]\n            if expected != '.' and expected != word[index]:\n                return False\n        return True\n    for word in words:\n        if matches(word):\n            return True\n    return False","steps":[{"id":"scan-first","title":"Test the pattern against the first word","codeLine":11,"summary":"words = [\"bad\", \"dad\", \"mad\"], pattern = \".ad\". The scan starts at \"bad\" and walks \".ad\" against b, a, d: the dot accepts b, then a and d match, so this word matches.","state":{"s":"bad","i":2,"labels":{"s":"word"}}},{"id":"scan-second","title":"A miss forces the scan onward","codeLine":10,"summary":"For a pattern like \".at\" that no word matches, \"bad\" fails at the last letter, so the scan moves on to \"dad\" and walks d, a, d all over again.","state":{"s":"dad","i":2,"labels":{"s":"word"}}},{"id":"scan-third","title":"Down to the last word","codeLine":10,"summary":"Still no match, so the scan reaches \"mad\" and walks m, a, d as well. Three words, every character re-read, for a single search.","state":{"s":"mad","i":2,"labels":{"s":"word"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"function matches(word) {\n    if (word.length != pattern.length) {\n        return false;\n    }\n    for (let index = 0; index < word.length; index++) {\n        const expected = pattern[index];\n        if (expected !== \".\" && expected !== word[index]) {\n            return false;\n        }\n    }\n    return true;\n}\nfor (const word of words) {\n    if (matches(word)) {\n        return true;\n    }\n}\nreturn false;","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":7,"8":8,"9":11,"10":13,"11":14,"12":15,"13":18},"statementBundles":{"4":{"startLine":3,"endLine":4},"8":{"startLine":8,"endLine":10},"9":{"startLine":11,"endLine":12},"12":{"startLine":15,"endLine":17}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"function matches(word: string): boolean {\n    if (word.length != pattern.length) {\n        return false;\n    }\n    for (let index = 0; index < word.length; index++) {\n        const expected = pattern[index];\n        if (expected !== \".\" && expected !== word[index]) {\n            return false;\n        }\n    }\n    return true;\n}\nfor (const word of words) {\n    if (matches(word)) {\n        return true;\n    }\n}\nreturn false;","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":7,"8":8,"9":11,"10":13,"11":14,"12":15,"13":18},"statementBundles":{"4":{"startLine":3,"endLine":4},"8":{"startLine":8,"endLine":10},"9":{"startLine":11,"endLine":12},"12":{"startLine":15,"endLine":17}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"private static boolean matches(String word, String pattern) {\n    if (word.length() != pattern.length()) {\n        return false;\n    }\n    for (int index = 0; index < word.length(); index++) {\n        String expected = String.valueOf(pattern.charAt(index));\n        if ((!\".\".equals(expected) && !String.valueOf(word.charAt(index)).equals(expected))) {\n            return false;\n        }\n    }\n    return true;\n}\n\nfor (String word : words) {\n    if (matches(word, pattern)) {\n        return true;\n    }\n}","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":7,"8":8,"9":11,"10":14,"11":15,"12":16},"statementBundles":{"4":{"startLine":3,"endLine":4},"8":{"startLine":8,"endLine":10},"9":{"startLine":11,"endLine":12},"12":{"startLine":16,"endLine":18}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"bool Matches(string word) {\n    if (word.Length != pattern.Length) {\n        return false;\n    }\n    for (int index = 0; index < word.Length; index++) {\n        char expected = pattern[index];\n        if (expected != '.' && expected != word[index]) {\n            return false;\n        }\n    }\n    return true;\n    return false;\n}\nforeach (string word in words) {\n    if (Matches(word)) {\n        return true;\n    }\n}\nreturn false;","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":7,"8":8,"9":11,"10":14,"11":15,"12":16,"13":19},"statementBundles":{"4":{"startLine":3,"endLine":4},"8":{"startLine":8,"endLine":10},"9":{"startLine":11,"endLine":13},"12":{"startLine":16,"endLine":18}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"auto matches = [&]( string word ) -> bool {\n    if (word.size() != pattern.size()) {\n        return false;\n    }\n    for (int index = 0; index < word.size(); index++) {\n        char expected = pattern[index];\n        if ((expected != '.' && expected != word[index])) {\n            return false;\n        }\n    }\n    return true;\n};\nfor (string word : words) {\n    if (matches(word)) {\n        return true;\n    }\n}\nreturn false;","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":7,"8":8,"9":11,"10":13,"11":14,"12":15,"13":18},"statementBundles":{"4":{"startLine":3,"endLine":4},"8":{"startLine":8,"endLine":10},"9":{"startLine":11,"endLine":12},"12":{"startLine":15,"endLine":17}}}}}},{"id":"cost-probe","kind":"case-probe","chapter":"The slow way","eyebrow":"Count the work","title":"How much does one search read against the flat list?","workspacePanel":"trace","summary":"The list holds w words, each up to length m, and a failing pattern is rejected only after the last one.","options":[{"id":"all-words","label":"Up to every character of every word, about w times m per search","rationale":"A flat list has no idea which word a pattern might fit, so it walks each of the w words character by character, up to m each, matching letters and wildcards as it goes. A pattern that matches nothing pays the full w times m, and every search pays it again.","isCorrect":true},{"id":"one-word","label":"Just the characters of the pattern, once","rationale":"That is the cost we want, but a list cannot reach it. With nothing grouping words by their letters, the only way to test a pattern is to try it against each stored word in turn.","isCorrect":false},{"id":"log-words","label":"About log w, because the list stays sorted","rationale":"Sorting helps find an exact word, but a wildcard like \".ad\" can match a scattered run of words, so a binary search cannot pin it down. The list never gets you below reading whole words.","isCorrect":false}],"answer":"About w times m per search. With words sitting in a flat list, every search re-walks each candidate character by character because there is no branch to follow for the pattern's next position."},{"id":"idea-bridge","kind":"info","chapter":"The idea","eyebrow":"Stop re-reading","title":"The flat list has no branches to follow","workspacePanel":"visualizer","body":["The flat list pays w times m because every search starts a fresh comparison against each stored word.","For \".ad\", the first position may match b, d, or m. After one of those choices, the search still has to match a and then d. The representation needs to expose the possible next letters at each pattern position."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"stacked-words-state","state":{"rows":[{"label":"bad","values":["b","a","d"],"changed":[1,2]},{"label":"dad","values":["d","a","d"],"changed":[1,2]},{"label":"mad","values":["m","a","d"],"changed":[1,2]}]}}]}},{"id":"shared-structure-probe","kind":"case-probe","chapter":"The idea","eyebrow":"Find the structure","title":"What lets \"bad\", \"dad\", and \"mad\" be walked one letter at a time?","workspacePanel":"visualizer","summary":"In \".ad\", the first position accepts any letter, while the next two positions must be a and d.","options":[{"id":"char-tree","label":"Make each word a path of single-character steps, so each letter is one node to walk","rationale":"Spell every word as a walk: b then a then d for \"bad\", with parallel paths for \"dad\" and \"mad\". Each node exposes the letters that can come next after the prefix used to reach it.","isCorrect":true},{"id":"sorted","label":"Sort the words so a binary search can find a match","rationale":"Order helps locate an exact word, but it does nothing for a wildcard. \".ad\" matches words that need not sit next to each other in sorted order, so you would still scan a run instead of walking one structure.","isCorrect":false},{"id":"by-length","label":"Group the words by length so equal-length words sit together","rationale":"Length tells you nothing about which letters branch where. \"bad\" and \"cup\" are both length three yet share no path, while \".ad\" needs the structure to branch by the actual letters at each step.","isCorrect":false}],"answer":"Make each word a path of one-character steps. From the start, the available first steps are b, d, and m. After taking b, the next available step is a, followed by d. The same one-position-at-a-time representation holds for the other stored words.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"forest-state","state":{"graph":{"nodes":[{"id":"b","label":"b"},{"id":"ba","label":"a"},{"id":"bad","label":"d"},{"id":"d","label":"d"},{"id":"da","label":"a"},{"id":"dad","label":"d"},{"id":"m","label":"m"},{"id":"ma","label":"a"},{"id":"mad","label":"d"}],"edges":[["b","ba"],["ba","bad"],["d","da"],["da","dad"],["m","ma"],["ma","mad"]],"visited":["bad","dad","mad"]}}}]}},{"id":"word-end-state-probe","kind":"case-probe","chapter":"The idea","eyebrow":"Complete the state","title":"What lets search(\"bad\") be false while search(\"badly\") is true?","workspacePanel":"visualizer","summary":"Only \"badly\" was added. Both searches follow b, a, and d before the shorter pattern runs out.","options":[{"id":"word-end-mark","label":"Mark each node where a stored word ends","rationale":"The d node lies on the path to \"badly\", but its word-end mark stays false because \"bad\" was never added. The y node carries the true mark for \"badly\".","isCorrect":true},{"id":"path-exists","label":"Treat any existing path as a stored word","rationale":"That would return true for \"bad\" as soon as the pattern ends at d, even though d exists only as part of the longer word \"badly\".","isCorrect":false},{"id":"root-length","label":"Keep only the longest stored length at the root","rationale":"One global length cannot identify which trie nodes finish stored words. Different branches can contain words of different lengths.","isCorrect":false}],"answer":"Mark the node where each added word ends. A path proves that a prefix exists; search succeeds only after the full pattern is consumed at a node whose word-end mark is true.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"badly-path-state","state":{"graph":{"nodes":[{"id":"b","label":"b"},{"id":"ba","label":"a"},{"id":"bad","label":"d"},{"id":"badl","label":"l"},{"id":"badly","label":"y"}],"edges":[["b","ba"],["ba","bad"],["bad","badl"],["badl","badly"]],"visited":["badly"],"current":"bad"}}}]}},{"id":"wildcard-branch-probe","kind":"case-probe","chapter":"The idea","eyebrow":"Find the structure","title":"On this forest, what must search(\".ad\") do at the dot?","workspacePanel":"visualizer","summary":"The pattern \".ad\" starts with a wildcard, and three first-letter paths leave the start: b, d, and m.","options":[{"id":"branch-all","label":"Try every first-letter child, and succeed if any one of them finishes the pattern","rationale":"A plain letter follows one child, but the dot stands for any letter, so it must try b, d, and m in turn. From each it continues with \"ad\"; the first branch that reaches a word-end node makes the whole search true. A small walk over the tree that branches at every dot is the entire idea.","isCorrect":true},{"id":"first-child","label":"Follow only the first child, since one match is all search needs","rationale":"One match is enough, but nothing about the dot says which child holds it, so committing to the first one before checking the rest is a guess. The dot has to keep its options open across all of them.","isCorrect":false},{"id":"mark-dot","label":"Add a child keyed on \".\" so the dot follows it like a normal letter","rationale":"No word contains a literal dot, so no such child exists. The dot is not stored in the tree; it is a search-time instruction to branch across whatever real children are present.","isCorrect":false}],"answer":"Try every child at the dot and succeed if any branch finishes the pattern. From the start, \".\" branches into b, d, and m; each continues with \"ad\" and reaches a word-end node, so the search returns true the moment one branch matches. A plain letter follows a single child, but a dot fans out into all of them.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"branch-state","state":{"graph":{"nodes":[{"id":"b","label":"b"},{"id":"ba","label":"a"},{"id":"bad","label":"d"},{"id":"d","label":"d"},{"id":"da","label":"a"},{"id":"dad","label":"d"},{"id":"m","label":"m"},{"id":"ma","label":"a"},{"id":"mad","label":"d"}],"edges":[["b","ba"],["ba","bad"],["d","da"],["da","dad"],["m","ma"],["ma","mad"]],"visited":["bad","dad","mad"],"current":"b","highlighted":["d","m"]}}}]}},{"id":"approach-selection","kind":"choice","source":"approach-selection","chapter":"The idea","eyebrow":"Pick the route","title":"Which way of storing the words supports the wildcard search?","workspacePanel":"visualizer","selection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"scan-all-words","name":"Scan every stored word","summary":"Keep all words in a list and match each one against the pattern, dot by dot.","decisionReason":"It answers every search correctly, but it re-reads all w words on each call, so a wildcard buys it nothing over a plain exact match.","complexity":{"time":"O(n*m) per search","space":"O(T)"},"tradeoffs":["Runs in O(n*m) per search time and uses O(T) space."],"isOptimal":false},{"id":"trie-dfs","name":"Trie with recursive wildcard search","summary":"Index stored words by their next character so a search advances one pattern position at a time.","decisionReason":"The trie exposes b, d, and m as the possible first letters for \".ad\" without comparing the pattern against three complete words. The dot rule can inspect those choices at the current node.","complexity":{"time":"O(m) insert, O(26^d * m) worst-case search","space":"O(T)"},"tradeoffs":["Runs in O(m) insert, O(26^d * m) worst-case search time and uses O(T) space."],"isOptimal":true}]},"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-state","state":{"graph":{"nodes":[{"id":"b","label":"b"},{"id":"ba","label":"a"},{"id":"bad","label":"d"},{"id":"d","label":"d"},{"id":"da","label":"a"},{"id":"dad","label":"d"},{"id":"m","label":"m"},{"id":"ma","label":"a"},{"id":"mad","label":"d"}],"edges":[["b","ba"],["ba","bad"],["d","da"],["da","dad"],["m","ma"],["ma","mad"]],"visited":["bad","dad","mad"]}}}]}},{"id":"prefix-state-probe","kind":"case-probe","chapter":"The idea","eyebrow":"Define the state","title":"At the a node on the b branch, what has search established?","workspacePanel":"visualizer","summary":"The pattern is \".ad\". The walk chose b for the dot, then followed a.","options":[{"id":"matched-prefix","label":"The consumed pattern \".a\" matches the stored prefix \"ba\" on this branch","rationale":"The path to the current node records b then a, while the search has consumed the dot and a. The node therefore represents one stored prefix still compatible with the pattern so far.","isCorrect":true},{"id":"matched-word","label":"The complete pattern already matches the stored word \"bad\"","rationale":"The final d has not been consumed yet. A complete-word match still requires following d and ending on a marked node.","isCorrect":false},{"id":"all-a-words","label":"Every stored word containing a anywhere is still possible","rationale":"A trie node records an ordered prefix. Words with a in another position do not reach this node after consuming the first two pattern positions.","isCorrect":false}],"answer":"The current node represents the stored prefix \"ba\" matching the consumed pattern prefix \".a\" on this branch. Search still has to match d and finish on a word-end node.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"matched-prefix-state","state":{"graph":{"nodes":[{"id":"b","label":"b"},{"id":"ba","label":"a"},{"id":"bad","label":"d"}],"edges":[["b","ba"],["ba","bad"]],"visited":["b","ba"],"current":"ba"}}}]}},{"id":"dry-run-setup","kind":"info","chapter":"Trace it","eyebrow":"Watch it move","title":"Add three words that share an ending, then search a wildcard","workspacePanel":"visualizer","body":["Each node keeps a small map from a character to its child, plus a mark for whether a word ends there. addWord spells the word out, following an existing child when the character is there and creating one when it is not, then marks the node it ends on.","\"bad\", \"dad\", and \"mad\" are already in the forest below, each its own short path, with their final d nodes marked as words. You will run search(\".ad\") and watch the dot branch into all three first letters before the \"ad\" tail finishes each one."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup-state","state":{"graph":{"nodes":[{"id":"b","label":"b"},{"id":"ba","label":"a"},{"id":"bad","label":"d"},{"id":"d","label":"d"},{"id":"da","label":"a"},{"id":"dad","label":"d"},{"id":"m","label":"m"},{"id":"ma","label":"a"},{"id":"mad","label":"d"}],"edges":[["b","ba"],["ba","bad"],["d","da"],["da","dad"],["m","ma"],["ma","mad"]],"visited":["bad","dad","mad"]}}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","chapter":"Trace it","eyebrow":"Trace the walk","title":"Branch search(\".ad\") into b, d, and m","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dot-branch","state":{"graph":{"nodes":[{"id":"b","label":"b"},{"id":"ba","label":"a"},{"id":"bad","label":"d"},{"id":"d","label":"d"},{"id":"da","label":"a"},{"id":"dad","label":"d"},{"id":"m","label":"m"},{"id":"ma","label":"a"},{"id":"mad","label":"d"}],"edges":[["b","ba"],["ba","bad"],["d","da"],["da","dad"],["m","ma"],["ma","mad"]],"visited":["bad","dad","mad"],"current":"b","highlighted":["d","m"]}}},{"id":"walk-bad","state":{"graph":{"nodes":[{"id":"b","label":"b"},{"id":"ba","label":"a"},{"id":"bad","label":"d"},{"id":"d","label":"d"},{"id":"da","label":"a"},{"id":"dad","label":"d"},{"id":"m","label":"m"},{"id":"ma","label":"a"},{"id":"mad","label":"d"}],"edges":[["b","ba"],["ba","bad"],["d","da"],["da","dad"],["m","ma"],["ma","mad"]],"visited":["bad","dad","mad"],"current":"ba","highlighted":["b"],"activeEdges":[["b","ba"]]}}},{"id":"finish-bad","state":{"graph":{"nodes":[{"id":"b","label":"b"},{"id":"ba","label":"a"},{"id":"bad","label":"d"},{"id":"d","label":"d"},{"id":"da","label":"a"},{"id":"dad","label":"d"},{"id":"m","label":"m"},{"id":"ma","label":"a"},{"id":"mad","label":"d"}],"edges":[["b","ba"],["ba","bad"],["d","da"],["da","dad"],["m","ma"],["ma","mad"]],"visited":["bad","dad","mad"],"current":"bad","highlighted":["ba"],"activeEdges":[["ba","bad"]]}}},{"id":"why-other-branches","state":{"graph":{"nodes":[{"id":"b","label":"b"},{"id":"ba","label":"a"},{"id":"bad","label":"d"},{"id":"d","label":"d"},{"id":"da","label":"a"},{"id":"dad","label":"d"},{"id":"m","label":"m"},{"id":"ma","label":"a"},{"id":"mad","label":"d"}],"edges":[["b","ba"],["ba","bad"],["d","da"],["da","dad"],["m","ma"],["ma","mad"]],"visited":["bad","dad","mad"],"current":"d","highlighted":["m"]}}}]},"beats":[{"id":"dot-branch","title":"The pattern \".ad\" opens with a dot. Which children does search try?","summary":"Three first-letter paths leave the start: b, d, and m.","prompt":"The pattern is \".ad\", and the first character is the wildcard \".\".","options":[{"id":"all-three","label":"All three children, b, d, and m, one branch at a time","rationale":"A dot stands for any letter, so search cannot pick one child in advance. It tries b, d, and m in turn, carrying the rest of the pattern, \"ad\", down each branch until one of them matches.","isCorrect":true},{"id":"only-b","label":"Only the b child, because it is the first one stored","rationale":"Order of storage does not decide a match. If b dead-ended while d matched, stopping at b would wrongly report false, so every child has to be tried.","isCorrect":false},{"id":"literal-dot","label":"A child keyed on \".\", if one exists","rationale":"No word holds a literal dot, so there is no such child. At search time, the dot fans out across the children of the current node.","isCorrect":false}],"answer":"All three children. The dot matches any letter, so search branches into b, d, and m, carrying \"ad\" down each. The first branch whose \"ad\" reaches a marked node ends the search with true."},{"id":"walk-bad","title":"Down the b branch, the next pattern letter is \"a\". What does search do?","summary":"Inside the b path, the only child is a, on the way to \"bad\".","prompt":"The remaining pattern after the dot is \"ad\", and the b node has a child for a.","options":[{"id":"follow-a","label":"Follow the single a child, since \"a\" is a plain letter","rationale":"A plain letter is not a wildcard, so it follows exactly the one matching child. The b node has an a child, so search steps onto it with \"d\" still left to match.","isCorrect":true},{"id":"branch-again","label":"Branch into every child again, the way the dot did","rationale":"Only a dot branches. A concrete letter like a follows its single matching child, and fans out to nothing, so the walk stays one step wide here.","isCorrect":false},{"id":"stop-here","label":"Stop and return true, because two characters already matched","rationale":"The pattern still has \"d\" left. search succeeds only once the whole pattern is consumed at a marked node, so it must keep walking.","isCorrect":false}],"answer":"Follow the single a child. \"a\" is a concrete letter, so it steps onto exactly the matching child of b, leaving \"d\" to match. Branching is reserved for the dot."},{"id":"finish-bad","title":"The last pattern letter \"d\" lands on the marked node. What does search return?","summary":"The b, a, d walk reaches the final d node, which is marked as the word \"bad\".","prompt":"Choose the return value for this branch.","options":[{"id":"true-marked","label":"True, this branch matches","rationale":"search needs the pattern fully matched and the final node marked. The b branch consumed \".ad\" exactly and landed on the marked end of \"bad\", so the search returns true at once.","isCorrect":true},{"id":"check-others","label":"It must still finish the d and m branches before answering","rationale":"One matching branch is enough. Once b reaches a marked node for the full pattern, search returns true immediately and never needs the other branches.","isCorrect":false},{"id":"false-prefix","label":"False, because \"ad\" is only the tail of the word","rationale":"The walk consumed every character and ended on a complete-word marker. That is a match.","isCorrect":false}],"answer":"True. The b branch consumed all of \".ad\" and finished on the marked d node that ends \"bad\", so search returns true without trying d or m."},{"id":"why-other-branches","title":"Suppose \"bad\" had not been stored. Would the d and m branches still matter?","summary":"The dot also opened the d and m branches, each carrying \"ad\".","prompt":"With \"bad\" gone, the b branch would dead-end, but \"dad\" and \"mad\" still sit under d and m.","options":[{"id":"yes-other","label":"Yes, search would try d next, walk \"ad\", and match \"dad\"","rationale":"A dead b branch is not the final answer. search backs out and tries the next child the dot opened, so it walks d, a, d, lands on the marked end of \"dad\", and returns true. Trying every branch is exactly what makes the dot correct.","isCorrect":true},{"id":"no-false","label":"No, a failed first branch means search returns false","rationale":"A dot fails only when every branch it opened fails. One dead branch just sends search to the next child, so a single failure cannot end the search.","isCorrect":false},{"id":"restart","label":"No, search restarts the whole pattern from the d node","rationale":"There is no restart. The dot already matched the first letter; the d and m branches resume from \"ad\", the unmatched tail, not from the beginning.","isCorrect":false}],"answer":"Yes. A dead b branch only sends search to the next child the dot opened, so it walks d, a, d to the marked end of \"dad\" and returns true. The dot must be free to try every child, because the match can hide under any of them."}]},{"id":"first-child-pitfall","kind":"pitfall","chapter":"Trace it","eyebrow":"Spot the trap","title":"Could the dot just follow the first child it finds?","workspacePanel":"trace","summary":"A mistaken version treats the dot like a letter and steps into one child, picking whichever child comes first. On \".ad\" with \"bad\" stored it even returns the right answer. Watch it on a forest where the first child dead-ends.","pitfall":"At a dot, the search below steps into the first child only, instead of trying every child, so it commits to one branch and never backs out.","whyItMatters":"With \"bat\" and \"dad\" stored, search(\".ad\") takes the first child b, walks a, then needs d but finds only t under \"bat\", so it returns false. The real match, \"dad\", sits under the d child it never tried. A dot has to try every child, because the matching word can hide under any of them.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"class TrieNode:\n    def __init__(self) -> None:\n        self.children: dict[str, TrieNode] = {}\n        self.is_end: bool = False\n\ndef search(node: TrieNode, pattern: str, i: int) -> bool:\n    def first_child(current: TrieNode) -> TrieNode | None:\n        for child in current.children.values():\n            return child\n        return None\n    if i == len(pattern):\n        return node.is_end\n    child = first_child(node)\n    if child is None:\n        return False\n    return search(child, pattern, i + 1)","steps":[{"id":"p-dot","title":"At the dot, it grabs the first child b","codeLine":13,"summary":"\"bat\" and \"dad\" are stored. Searching \".ad\", this version takes the first child, b, and commits to it without remembering d is also there.","state":{"graph":{"nodes":[{"id":"b","label":"b"},{"id":"ba","label":"a"},{"id":"bat","label":"t"},{"id":"d","label":"d"},{"id":"da","label":"a"},{"id":"dad","label":"d"}],"edges":[["b","ba"],["ba","bat"],["d","da"],["da","dad"]],"visited":["bat","dad"],"current":"b","highlighted":["d"]}}},{"id":"p-walk-a","title":"It walks a, still inside the b branch","codeLine":13,"summary":"The next pattern letter is a, and the b node has an a child, so the walk steps onto it. So far the b branch looks fine.","state":{"graph":{"nodes":[{"id":"b","label":"b"},{"id":"ba","label":"a"},{"id":"bat","label":"t"},{"id":"d","label":"d"},{"id":"da","label":"a"},{"id":"dad","label":"d"}],"edges":[["b","ba"],["ba","bat"],["d","da"],["da","dad"]],"visited":["bat","dad"],"current":"ba","highlighted":["b"],"activeEdges":[["b","ba"]]}}},{"id":"p-dead-end","title":"It needs d but finds only t, and gives up","codeLine":4,"summary":"The last pattern letter is d, but the only child here spells \"bat\", ending in t. This version returns false, even though \"dad\" matches \".ad\" under the d branch it never tried.","state":{"graph":{"nodes":[{"id":"b","label":"b"},{"id":"ba","label":"a"},{"id":"bat","label":"t"},{"id":"d","label":"d"},{"id":"da","label":"a"},{"id":"dad","label":"d"}],"edges":[["b","ba"],["ba","bat"],["d","da"],["da","dad"]],"visited":["bat","dad"],"current":"ba","highlighted":["bat"]}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"class TrieNode {\n    constructor() {\n        this.children = new Map();\n        this.isEnd = false;\n    }\n}\n\nfunction firstChild(current) {\n    for (const child of [...current.children.values()]) {\n        return child;\n    }\n    return null;\n}\nif (i == pattern.length) {\n    return node.isEnd;\n}\nconst child = firstChild(node);\nif (child === null) {\n    return false;\n}\nreturn search(child, pattern, (i + 1));","lineMap":{"3":3,"4":4,"8":9,"9":10,"10":12,"11":14,"12":15,"13":17,"14":18,"15":19,"16":21},"statementBundles":{"4":{"startLine":4,"endLine":8},"9":{"startLine":10,"endLine":11},"10":{"startLine":12,"endLine":13},"12":{"startLine":15,"endLine":16},"15":{"startLine":19,"endLine":20}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"class TrieNode {\n    children: Map<string, TrieNode>;\n    isEnd: boolean;\n\n    constructor() {\n        this.children = new Map();\n        this.isEnd = false;\n    }\n}\n\nfunction firstChild(current: TrieNode): TrieNode | null {\n    for (const child of [...current.children.values()]) {\n        return child;\n    }\n    return null;\n}\nif (i == pattern.length) {\n    return node.isEnd;\n}\nconst child = firstChild(node);\nif (child === null) {\n    return false;\n}\nreturn search(child, pattern, (i + 1));","lineMap":{"3":6,"4":7,"8":12,"9":13,"10":15,"11":17,"12":18,"13":20,"14":21,"15":22,"16":24},"statementBundles":{"4":{"startLine":7,"endLine":11},"9":{"startLine":13,"endLine":14},"10":{"startLine":15,"endLine":16},"12":{"startLine":18,"endLine":19},"15":{"startLine":22,"endLine":23}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"class TrieNode {\n    Map<String, TrieNode> children;\n    boolean isEnd;\n\n    public TrieNode() {\n        this.children = new HashMap<String, TrieNode>();\n        this.isEnd = false;\n    }\n}\n\nprivate static TrieNode firstChild(TrieNode current) {\n    for (TrieNode child : new ArrayList<TrieNode>(current.children.values())) {\n        return child;\n    }\n    return null;\n}\n\nif (i == pattern.length()) {\n    return node.isEnd;\n}\nTrieNode child = firstChild(node);\nif (Objects.equals(child, null)) {\n    return false;\n}\nreturn search(child, pattern, (i + 1));","lineMap":{"3":6,"4":7,"8":12,"9":13,"10":15,"11":18,"12":19,"13":21,"14":22,"15":23,"16":25},"statementBundles":{"4":{"startLine":7,"endLine":11},"9":{"startLine":13,"endLine":14},"10":{"startLine":15,"endLine":16},"12":{"startLine":19,"endLine":20},"15":{"startLine":23,"endLine":24}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"class TrieNode\n{\n    public Dictionary<string, TrieNode> children;\n    public bool isEnd;\n\n    public TrieNode()\n    {\n        this.children = new Dictionary<string, TrieNode>();\n        this.isEnd = false;\n    }\n}\n\nTrieNode FirstChild(TrieNode current) {\n    foreach (var child in current.children.Values) {\n        return child;\n    }\n    return null;\n    return null;\n}\nif (i == pattern.Length) {\n    return node.isEnd;\n}\nTrieNode child = FirstChild(node);\nif (child == null) {\n    return false;\n}\nreturn Search(child, pattern, i + 1);","lineMap":{"3":8,"4":9,"8":14,"9":15,"10":17,"11":20,"12":21,"13":23,"14":24,"15":25,"16":27},"statementBundles":{"4":{"startLine":9,"endLine":13},"9":{"startLine":15,"endLine":16},"10":{"startLine":17,"endLine":19},"12":{"startLine":21,"endLine":22},"15":{"startLine":25,"endLine":26}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"struct TrieNode {\n    unordered_map<string, TrieNode*> children;\n    bool is_end;\n\n    TrieNode() {\n        this->children = unordered_map<string, TrieNode*>{};\n        this->is_end = false;\n    }\n};\n\nauto first_child = [&]( TrieNode* current ) -> TrieNode* {\n    for (const auto& [key, child] : current->children) {\n        return child;\n    }\n    return nullptr;\n};\nif (i == pattern.size()) {\n    return node->is_end;\n}\nTrieNode* child = first_child(node);\nif (child == nullptr) {\n    return false;\n}\nreturn search(child, pattern, (i + 1));","lineMap":{"3":6,"4":7,"8":12,"9":13,"10":15,"11":17,"12":18,"13":20,"14":21,"15":22,"16":24},"statementBundles":{"4":{"startLine":7,"endLine":11},"9":{"startLine":13,"endLine":14},"10":{"startLine":15,"endLine":16},"12":{"startLine":18,"endLine":19},"15":{"startLine":22,"endLine":23}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Where do the dot and the word-end mark get tested hardest?","workspacePanel":"visualizer","body":["Branching at every dot and reading the word-end mark only when the whole pattern is consumed is what carried the search through \".ad\".","Now push on those two rules with patterns that are all dots, or that lead a dot into a branch where no child can finish, and decide what each one returns."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"graph":{"nodes":[{"id":"b","label":"b"},{"id":"ba","label":"a"},{"id":"bad","label":"d"},{"id":"d","label":"d"},{"id":"da","label":"a"},{"id":"dad","label":"d"},{"id":"m","label":"m"},{"id":"ma","label":"a"},{"id":"mad","label":"d"}],"edges":[["b","ba"],["ba","bad"],["d","da"],["da","dad"],["m","ma"],["ma","mad"]],"visited":["bad","dad","mad"]}}}]}},{"id":"all-dots-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"With \"bad\", \"dad\", \"mad\" stored, what does search(\"...\") return?","workspacePanel":"visualizer","summary":"Every character of the pattern \"...\" is a dot, and every stored word has exactly three letters.","options":[{"id":"true-length","label":"True, because each dot branches and some length-three path ends at a marked node","rationale":"The first dot branches into b, d, and m; the next dots match a then d down any of those paths. Each reaches a marked three-letter word, so the pattern is fully consumed at a marked node and search returns true.","isCorrect":true},{"id":"false-nomatch","label":"False, because \"...\" is not one of the stored words","rationale":"A pattern is never compared as a literal string. Each dot matches a real letter along a path, so \"...\" matches any stored word of length three, and three such words exist.","isCorrect":false},{"id":"true-any","label":"True, because dots always match no matter what is stored","rationale":"Dots still need a path and a marked end. If no stored word had length three, all the branching would dead-end and search would return false; it is true here only because length-three words exist.","isCorrect":false}],"answer":"True. Each dot matches one real letter, so \"...\" matches any stored word of length three. The branches reach the marked ends of \"bad\", \"dad\", and \"mad\", and the first one consumed at a marked node makes the search true.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"all-dots-state","state":{"graph":{"nodes":[{"id":"b","label":"b"},{"id":"ba","label":"a"},{"id":"bad","label":"d"},{"id":"d","label":"d"},{"id":"da","label":"a"},{"id":"dad","label":"d"},{"id":"m","label":"m"},{"id":"ma","label":"a"},{"id":"mad","label":"d"}],"edges":[["b","ba"],["ba","bad"],["d","da"],["da","dad"],["m","ma"],["ma","mad"]],"visited":["bad","dad","mad"],"current":"b","highlighted":["d","m"]}}}]}},{"id":"dot-dead-branch-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"What does search(\".at\") return when no stored word ends in \"at\"?","workspacePanel":"visualizer","summary":"The stored words are \"bad\", \"dad\", and \"mad\", and the pattern \".at\" ends in t.","options":[{"id":"false-all-fail","label":"False, because every branch the dot opened fails to match the final t","rationale":"The dot tries b, d, and m; each has an a child, but the next node is d, not t, so every branch dead-ends at the last character. A dot returns false only when all of its branches fail, and here they all do.","isCorrect":true},{"id":"true-some","label":"True, because the dot matched a real first letter","rationale":"Matching the dot is only the first step. The rest of the pattern, \"at\", still has to be walked to a marked node, and no path offers a t after a, so the search fails.","isCorrect":false},{"id":"error-branch","label":"It cannot decide, because three branches disagree","rationale":"Disagreement is not an error. search just tries each branch; if every one returns false, the dot returns false. Three failing branches give a clean false.","isCorrect":false}],"answer":"False. The dot opens b, d, and m, and each walks to an a node whose only child is d, never t. Every branch fails at the final character, and a dot is false only when all its branches are, so the search returns false.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dead-branch-state","state":{"graph":{"nodes":[{"id":"b","label":"b"},{"id":"ba","label":"a"},{"id":"bad","label":"d"},{"id":"d","label":"d"},{"id":"da","label":"a"},{"id":"dad","label":"d"},{"id":"m","label":"m"},{"id":"ma","label":"a"},{"id":"mad","label":"d"}],"edges":[["b","ba"],["ba","bad"],["d","da"],["da","dad"],["m","ma"],["ma","mad"]],"visited":["bad","dad","mad"],"current":"ba","highlighted":["da","ma"]}}}]}},{"id":"ready-to-code","kind":"info","chapter":"Code","eyebrow":"Get ready to code","title":"Build the wildcard dictionary","workspacePanel":"visualizer","summary":"Now turn the tree into code: give each node a child map and a word-end mark, start the dictionary with one root, spell each added word out and mark where it ends, then walk a search down one child for a letter and every child for a dot.","body":["Give each node a small map from character to child and a word-end mark, and start the dictionary with one empty root. addWord spells the word out, following a child when the character is there and creating one when it is not, then marks the node it ends on.","search walks the pattern from the root. For a plain letter it follows the one matching child, or turns back if none exists. For a dot it tries every child in turn, succeeding as soon as one branch matches. When the pattern runs out, it reports the word-end mark on the node it landed on."],"ctaLabel":"Start coding","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"graph":{"nodes":[{"id":"b","label":"b"},{"id":"ba","label":"a"},{"id":"bad","label":"d"},{"id":"d","label":"d"},{"id":"da","label":"a"},{"id":"dad","label":"d"},{"id":"m","label":"m"},{"id":"ma","label":"a"},{"id":"mad","label":"d"}],"edges":[["b","ba"],["ba","bad"],["d","da"],["da","dad"],["m","ma"],["ma","mad"]],"visited":["bad","dad","mad"]}}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the wildcard trie","eyebrow":"Code the rule","summary":"Build the node, the root, the insert walk, then the search that branches only at a dot.","workspacePanel":"code","checkpoints":[{"id":"node-class","title":"Create trie nodes","description":"Give each trie node child storage and a terminal marker.","commonMistakes":["Missing the terminal marker","Sharing one child map across all nodes"],"hint":"Every node needs its own child map and an is-word flag.","semanticSpec":{"intent":"Initialize reusable trie node state.","doneWhen":"A trie node initializes child-link storage and terminal word state.","shouldFailWhen":"This step should fail if nodes cannot store child edges or word endings.","roles":["trie node","children","terminal marker"],"mustProve":["Each node owns child-link state.","Each node owns terminal word state."],"mustNotAccept":["A node that stores only children and no terminal marker."],"proofSnippets":[{"id":"py-word-dictionary-node-class","language":"python","code":"class TrieNode:\n    def __init__(self):\n        child_store = {}\n        self.children = child_store\n        self.is_end = False"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"initializes_trie_node_state","scope":"node-class","readMode":"tree-trie-value-query-v1"}]}},{"id":"trie-root","title":"Initialize the root","description":"Create one shared root node for all inserted words and searches.","commonMistakes":["Creating a new root inside each method","Leaving root uninitialized"],"hint":"The dictionary object should keep one persistent root.","semanticSpec":{"intent":"Initialize the persistent trie root.","doneWhen":"The WordDictionary constructor stores a root trie node.","shouldFailWhen":"This step should fail if root state is missing or local to a method.","roles":["dictionary object","root trie node"],"mustProve":["The root node is persistent instance state."],"mustNotAccept":["A root variable created only inside addWord or search."],"proofSnippets":[{"id":"py-word-dictionary-trie-root","language":"python","code":"class TrieNode:\n    def __init__(self):\n        child_store = {}\n        self.children = child_store\n        self.is_end = False\n\nclass WordDictionary:\n    def __init__(self):\n        self.root = TrieNode()"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"initializes_trie_root","scope":"trie-class","readMode":"tree-trie-value-query-v1"}]}},{"id":"add-word","title":"Insert words","description":"Walk the trie, create missing child nodes, and mark the final node as a complete word.","commonMistakes":["Not creating missing child nodes","Forgetting to mark the final node"],"hint":"Insertion is the standard trie path walk followed by a terminal marker write.","semanticSpec":{"intent":"Insert a word into the trie.","doneWhen":"addWord walks or creates one child edge per character and writes the terminal marker at the end.","shouldFailWhen":"This step should fail if words are stored only in a list or the terminal marker is never written.","roles":["word","trie path","terminal marker"],"mustProve":["The path walk creates missing trie nodes.","The final node is marked as a complete word."],"mustNotAccept":["Only storing the raw word outside the trie."],"proofSnippets":[{"id":"py-word-dictionary-add-word","language":"python","code":"class TrieNode:\n    def __init__(self):\n        self.children = {}\n        self.is_end = False\n\nclass WordDictionary:\n    def __init__(self):\n        self.root = TrieNode()\n\n    def addWord(self, word: str) -> None:\n        node = self.root\n        for char in word:\n            if char not in node.children:\n                node.children[char] = TrieNode()\n            node = node.children[char]\n        node.is_end = True"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"inserts_trie_word","scope":"insert-method","readMode":"tree-trie-value-query-v1"}]}},{"id":"wildcard-search","title":"Return wildcard search result","description":"DFS through the trie, following exact characters directly and branching over all children for ., then return whether the pattern reaches a terminal word.","commonMistakes":["Treating '.' as a literal child key","Returning true before checking the terminal marker","Advancing to only one child for a wildcard"],"hint":"The recursive state is the pattern index plus the current trie node; the public search returns the DFS result.","semanticSpec":{"intent":"Implement trie DFS search with wildcard branch expansion.","doneWhen":"search starts from the root, returns the terminal marker at the end of the pattern, recursively tries all children for ., follows indexed child links for normal characters, and returns the DFS result.","shouldFailWhen":"This step should fail if wildcard search does not recursively branch over child nodes.","roles":["pattern index","current trie node","wildcard branch"],"mustProve":["The recursive base case returns the current node's terminal marker.","A wildcard loops over child links and recurses into each child.","A normal character recurses into the indexed child link."],"mustNotAccept":["Checking only exact characters.","Scanning all stored words outside the trie."],"proofSnippets":[{"id":"py-word-dictionary-wildcard-search","language":"python","code":"class TrieNode:\n    def __init__(self):\n        self.children = {}\n        self.is_end = False\n\nclass WordDictionary:\n    def __init__(self):\n        self.root = TrieNode()\n\n    def addWord(self, word: str) -> None:\n        node = self.root\n        for char in word:\n            if char not in node.children:\n                node.children[char] = TrieNode()\n            node = node.children[char]\n        node.is_end = True\n\n    def search(self, word: str) -> bool:\n        def dfs(index: int, node: TrieNode) -> bool:\n            if index == len(word):\n                return node.is_end\n            char = word[index]\n            if char == '.':\n                for child in node.children.values():\n                    if dfs(index + 1, child):\n                        return True\n                return False\n            if char not in node.children:\n                return False\n            return dfs(index + 1, node.children[char])\n\n        return dfs(0, self.root)"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"searches_wildcard_trie_word","scope":"wildcard-search","readMode":"tree-trie-value-query-v1"}]}}]},{"id":"complete","kind":"complete","chapter":"Code","eyebrow":"Take it with you","title":"What to carry forward","workspacePanel":"code","summary":"A search walks one child for a letter and every child for a dot.","body":["Words that begin alike share their opening steps, so the dictionary becomes a tree where each node is one character and each word is a path. addWord spells the word out and marks the node it ends on.","search walks the pattern down that tree. A plain letter follows a single child; a dot fans out into every child and succeeds if any branch finishes. The match is real only when the whole pattern is consumed at a marked node."],"takeaways":[{"title":"A dot branches; a letter does not","body":"A plain letter follows the one matching child, so the walk stays one step wide, while a dot tries every child at that depth, which is why \".ad\" reaches \"bad\", \"dad\", and \"mad\" but \".at\" reaches none of them."},{"title":"A match needs the whole pattern and a marked node","body":"search succeeds only when the pattern is fully consumed at a word-end mark, so \"...\" matches a length-three word like \"bad\" while \"..\" cannot, because the mark sits one node deeper."},{"title":"Sharing prefixes pays off","body":"Because the words collapse into one tree, a search without dots costs O(m) in the pattern length instead of the flat list O(w times m), and the dot only multiplies work where it actually appears, up to O(26^d) over the d wildcard positions."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
