{"id":"stream-of-characters","title":"Stream of Characters","difficulty":"hard","patterns":["trie"],"primaryConcept":"trie-basics","concepts":["trie-basics"],"problemForm":"core","companies":["Google","Amazon","Meta","Microsoft"],"category":"trees-graphs","executionStyle":"ops-class","compareMode":"exact","syntheticTestConfig":{"inputShape":"operations","primaryParam":"operations","secondaryParam":"arguments","sizeMetric":"op-count-plus-word-lengths","opVocabulary":[{"name":"StreamChecker","arity":1,"argTypes":["string[]"],"weight":1},{"name":"query","arity":1,"argTypes":["string"],"weight":6}]},"description":"Design a `StreamChecker` class that receives a list of words.\n\nImplement `query(letter)` so each call appends `letter` to the stream and returns whether any suffix of the current stream equals one of the stored words.","examples":[{"input":"streamChecker = StreamChecker([\"cd\", \"f\", \"kl\"])\nstreamChecker.query(\"a\")\nstreamChecker.query(\"b\")\nstreamChecker.query(\"c\")\nstreamChecker.query(\"d\")","output":"[null,false,false,false,true]","explanation":"After querying \"d\", the stream suffix \"cd\" matches a stored word."},{"input":"streamChecker = StreamChecker([\"hell\", \"hello\"])\nstreamChecker.query(\"h\")\nstreamChecker.query(\"e\")\nstreamChecker.query(\"l\")\nstreamChecker.query(\"l\")","output":"[null,false,false,false,true]","explanation":"The suffix \"hell\" becomes available after the fourth query."}],"constraints":[{"id":"1-len-words-2000","text":"1 <= len(words) <= 2000"},{"id":"1-len-words-i-200","text":"1 <= len(words[i]) <= 200"},{"id":"words-i-consists-only-of-lowercase-english-letters","text":"words[i] consists only of lowercase English letters"},{"id":"letter-is-a-lowercase-english-letter","text":"letter is a lowercase English letter"},{"id":"at-most-40000-calls-will-be-made-to-query","text":"At most 40000 calls will be made to query"}],"starterCode":"class TrieNode:\n    def __init__(self):\n        self.children = {}\n        self.is_end = False\n\nclass StreamChecker:\n    def __init__(self, words: list[str]):\n        # Your code here\n        pass\n\n    def query(self, letter: str) -> bool:\n        # Your code here\n        pass","functionName":"StreamChecker","testCases":[{"id":"1","input":{"operations":["StreamChecker","query","query","query","query","query","query","query","query","query","query","query","query"],"arguments":[[["cd","f","kl"]],["a"],["b"],["c"],["d"],["e"],["f"],["g"],["h"],["i"],["j"],["k"],["l"]]},"expected":[null,false,false,false,true,false,true,false,false,false,false,false,true],"description":"Canonical suffix-stream example."},{"id":"2","input":{"operations":["StreamChecker","query","query","query"],"arguments":[[["a"]],["a"],["b"],["a"]]},"expected":[null,true,false,true],"description":"Single-letter words match only the latest capped character."},{"id":"3","input":{"operations":["StreamChecker","query","query","query"],"arguments":[[["ab","bc","abc"]],["a"],["b"],["c"]]},"expected":[null,false,true,true],"description":"Overlapping words can match on consecutive queries."},{"id":"4","input":{"operations":["StreamChecker","query","query","query","query","query"],"arguments":[[["hell","hello"]],["h"],["e"],["l"],["l"],["o"]]},"expected":[null,false,false,false,true,true],"description":"A shorter word and a longer word share the same reversed path."},{"id":"5","input":{"operations":["StreamChecker","query","query","query","query"],"arguments":[[["cd","de","f"]],["c"],["d"],["e"],["f"]]},"expected":[null,false,true,true,true],"description":"Different suffix lengths can match at different times."},{"id":"h1","input":{"operations":["StreamChecker","query","query"],"arguments":[[["kl"]],["k"],["l"]]},"expected":[null,false,true],"description":"A two-character word should not match after only the first character."},{"id":"h2","input":{"operations":["StreamChecker","query","query"],"arguments":[[["x","xy"]],["x"],["y"]]},"expected":[null,true,true],"description":"A terminal node can exist before a longer continuation."},{"id":"h3","input":{"operations":["StreamChecker","query","query","query","query"],"arguments":[[["abc"]],["a"],["b"],["x"],["c"]]},"expected":[null,false,false,false,false],"description":"A broken suffix path should prevent stale partial matches."},{"id":"h4","input":{"operations":["StreamChecker","query","query","query"],"arguments":[[["a","aa","aaa"]],["a"],["a"],["a"]]},"expected":[null,true,true,true],"description":"Repeated characters can match several terminal depths."},{"id":"h5","input":{"operations":["StreamChecker","query","query","query","query"],"arguments":[[["miss","is"]],["m"],["i"],["s"],["s"]]},"expected":[null,false,false,true,true],"description":"A short suffix can match before the longer word finishes."},{"id":"public-11","input":{"operations":["StreamChecker","query","query","query","query"],"arguments":[[["ab","bab","bc"]],["b"],["a"],["b"],["c"]]},"expected":[null,false,false,true,true],"description":"Suffix matching should not confuse reversed partial prefixes before a full word appears."},{"id":"public-12","input":{"operations":["StreamChecker","query","query","query","query","query"],"arguments":[[["xyz","z"]],["x"],["y"],["z"],["x"],["z"]]},"expected":[null,false,false,true,false,true],"description":"A single-letter terminal can match repeatedly after intervening misses."},{"id":"public-13","input":{"operations":["StreamChecker","query","query","query","query","query"],"arguments":[[["long"]],["l"],["o"],["n"],["g"],["g"]]},"expected":[null,false,false,false,true,false],"description":"A completed long suffix should disappear once a new trailing character breaks it."},{"id":"public-14","input":{"operations":["StreamChecker","query","query","query"],"arguments":[[["a","ba","cba"]],["c"],["b"],["a"]]},"expected":[null,false,false,true],"description":"Nested suffix words only match when the stream ends at their shared terminal."}],"hints":[{"level":1,"content":"Each query asks about suffixes of the stream, not prefixes."},{"level":2,"content":"Store each word reversed so a suffix check becomes a forward trie walk from the newest character backward."},{"level":3,"content":"The query only needs to scan up to the longest stored word."}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which implementation answers each suffix query without scanning every word?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"scan-all-words","name":"Re-check every word against the stream tail","summary":"On each letter, compare the tail of the stream against every stored word.","decisionReason":"It answers correctly, but it re-reads all w words on every one of the up to 40000 queries, so the same comparisons repeat letter after letter.","complexity":{"time":"O(w * m) per query","space":"O(L)"},"tradeoffs":["It is simple, but every query pays for every word again, even though the words never change."],"isOptimal":false},{"id":"reversed-trie","name":"Reversed-word trie walked from the newest letter","summary":"Insert each word back to front, then on a query walk the trie from the newest stream letter backward, stopping at any word-end mark.","decisionReason":"Reversing the words turns a suffix question into one walk from the newest letter, and words that end alike share that walk, so each query costs only the length of the longest word.","complexity":{"time":"O(L) per query","space":"O(total characters + L)"},"tradeoffs":["It walks at most L steps per query and reuses shared endings, at the cost of building and storing the trie once."],"isOptimal":true}]},"codingCheckpoints":[{"id":"node-class","title":"Create trie nodes","description":"Give each node child links and a terminal marker.","commonMistakes":["Storing only one child","Forgetting the terminal marker"],"hint":"Each node needs a map from character to child and a boolean for word endings.","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 children or word endings.","roles":["trie node","children","terminal marker"],"mustProve":["Trie node state includes child storage and terminal state."],"mustNotAccept":["Flat word lists without trie nodes."],"equivalentVariants":["Use dictionaries, maps, or arrays for child links."]},"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 root and stream","description":"Create the trie root and the bounded stream buffer.","commonMistakes":["Building a new root on every query","Not keeping recent stream letters"],"hint":"The constructor owns both the root node and the stream state.","semanticSpec":{"intent":"Initialize persistent trie root state.","doneWhen":"The constructor stores a root trie node.","shouldFailWhen":"This step should fail if the query cannot start from a persistent trie root.","roles":["trie root","stream buffer"],"mustProve":["A persistent trie root is initialized by the class constructor."],"mustNotAccept":["Creating only local roots inside query."],"equivalentVariants":["Use root, head, or another persistent field for the trie root."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"initializes_trie_root","scope":"trie-class","readMode":"tree-trie-value-query-v1"}]}},{"id":"insert-reversed-words","title":"Insert reversed words","description":"Walk each word from back to front and mark its terminal trie node.","commonMistakes":["Inserting words in the original direction","Forgetting to mark complete words"],"hint":"A stream suffix should line up with a forward walk from the newest letter.","semanticSpec":{"intent":"Insert stored words as trie paths.","doneWhen":"The constructor creates missing trie nodes while scanning word characters and marks terminal nodes.","shouldFailWhen":"This step should fail if words are only kept in a flat list.","roles":["word","trie path","terminal marker"],"mustProve":["Words are represented as trie paths with terminal markers."],"mustNotAccept":["Checking every word directly on each query."],"equivalentVariants":["Reverse each word first or iterate its characters from right to left."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"inserts_trie_word","scope":"insert-method","readMode":"tree-trie-value-query-v1"}]}},{"id":"query-suffix-path","title":"Walk query suffix","description":"After adding a letter, walk backward through the stream using trie child links.","commonMistakes":["Walking from the oldest stream letter","Continuing after a missing child"],"hint":"The newest character is the first trie step.","semanticSpec":{"intent":"Use trie child links to test stream suffixes.","doneWhen":"query follows trie links through recent stream characters and stops on missing paths.","shouldFailWhen":"This step should fail if query does not traverse trie child links.","roles":["stream character","current trie node","child link"],"mustProve":["Query advances through trie child links based on the stream."],"mustNotAccept":["Scanning stored words without trie traversal."],"equivalentVariants":["Store the stream as a list, string, deque, or capped buffer."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"checks_trie_prefix","scope":"startswith-method","readMode":"tree-trie-value-query-v1"}]}},{"id":"trie-workflow","title":"Complete trie workflow","description":"Combine reversed insertion with suffix queries that return when a terminal node is reached.","commonMistakes":["Returning true for any prefix instead of a complete word","Never checking terminal markers during query"],"hint":"A query matches only when a walked trie node marks the end of a stored word.","semanticSpec":{"intent":"Assemble the full trie-backed stream-checking workflow.","doneWhen":"The solution initializes trie state, inserts words, and queries through trie links.","shouldFailWhen":"This step should fail if the trie pieces are not connected into one workflow.","roles":["reversed trie","stream query","terminal marker"],"mustProve":["The solution has a coherent trie workflow."],"mustNotAccept":["Independent code fragments that do not form a working trie checker."],"equivalentVariants":["Use helper methods or build the trie directly in the constructor."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"workflow","readMode":"tree-trie-value-query-v1"}]}}],"slides":[{"id":"opener","kind":"info","chapter":"The problem","eyebrow":"Read the problem","title":"Answer suffix questions over a growing stream","workspacePanel":"problem","body":["You store a fixed list of lowercase words once. Then letters arrive one at a time, building a single growing stream. After each new letter, query(letter) must answer one question: does any suffix of the stream so far exactly equal one of the stored words?","A query lands after every single letter, so whatever answers it has to stay cheap as the stream and its history keep growing."]},{"id":"brute-force","kind":"code-trace","chapter":"The slow way","eyebrow":"The obvious way","title":"Re-check every stored word on every letter","summary":"After each letter, line up each stored word against the end of the stream and compare character by character. It answers correctly. Watch how much it re-reads.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def query(words: list[str], stream: list[str]) -> bool:\n    for word in words:\n        if len(word) > len(stream):\n            continue\n        match = True\n        for k in range(len(word)):\n            stream_idx = len(stream) - len(word) + k\n            if stream[stream_idx] != word[k]:\n                match = False\n        if match:\n            return True\n    return False","steps":[{"id":"check-cd-c","title":"Line \"cd\" up against the tail, compare c","codeLine":8,"summary":"Stream is \"abcd\". To test \"cd\", stream_idx points at position 2, comparing its first letter c there.","state":{"nums":["a","b","c","d"],"i":2,"word":"cd","labels":{"nums":"stream","i":"stream_idx"}}},{"id":"check-cd-d","title":"Then compare d at the next position","codeLine":8,"summary":"\"cd\" matches here, c then d against positions 2 and 3 as stream_idx advances, but confirming it still re-read both tail letters.","state":{"nums":["a","b","c","d"],"i":3,"word":"cd","labels":{"nums":"stream","i":"stream_idx"}}},{"id":"check-f","title":"Move on and re-read the tail for \"f\"","codeLine":2,"summary":"A stream like \"abcf\" would force the next word too, comparing \"f\" against position 3, walking the tail again for a different word.","state":{"nums":["a","b","c","d"],"i":3,"word":"f","labels":{"nums":"stream","i":"stream_idx"}}},{"id":"check-kl","title":"And again for \"kl\"","codeLine":2,"summary":"A third word means a third pass over the tail, k then l against positions 2 and 3. Every letter that arrives walks all stored words again, though the words never changed.","state":{"nums":["a","b","c","d"],"i":2,"word":"kl","labels":{"nums":"stream","i":"stream_idx"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"for (const word of words) {\n    if (word.length > stream.length) {\n        continue;\n    }\n    let match = true;\n    for (let k = 0; k < word.length; k++) {\n        const streamIdx = (stream.length - word.length) + k;\n        if (stream[streamIdx] !== word[k]) {\n            match = false;\n        }\n    }\n    if (match) {\n        return true;\n    }\n}\nreturn false;","lineMap":{"2":1,"3":2,"4":3,"5":5,"6":6,"7":7,"8":8,"9":9,"10":12,"11":13,"12":16},"statementBundles":{"4":{"startLine":3,"endLine":4},"9":{"startLine":9,"endLine":11},"11":{"startLine":13,"endLine":15}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"for (const word of words) {\n    if (word.length > stream.length) {\n        continue;\n    }\n    let match = true;\n    for (let k = 0; k < word.length; k++) {\n        const streamIdx = (stream.length - word.length) + k;\n        if (stream[streamIdx] !== word[k]) {\n            match = false;\n        }\n    }\n    if (match) {\n        return true;\n    }\n}\nreturn false;","lineMap":{"2":1,"3":2,"4":3,"5":5,"6":6,"7":7,"8":8,"9":9,"10":12,"11":13,"12":16},"statementBundles":{"4":{"startLine":3,"endLine":4},"9":{"startLine":9,"endLine":11},"11":{"startLine":13,"endLine":15}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"for (String word : words) {\n    if (word.length() > stream.size()) {\n        continue;\n    }\n    boolean match = true;\n    for (int k = 0; k < word.length(); k++) {\n        int streamIdx = (stream.size() - word.length()) + k;\n        if (!String.valueOf(word.charAt(k)).equals(stream.get(streamIdx))) {\n            match = false;\n        }\n    }\n    if (match) {\n        return true;\n    }\n}","lineMap":{"2":1,"3":2,"4":3,"5":5,"6":6,"7":7,"8":8,"9":9,"10":12,"11":13},"statementBundles":{"4":{"startLine":3,"endLine":4},"9":{"startLine":9,"endLine":11},"11":{"startLine":13,"endLine":15}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"foreach (string word in words) {\n    if (word.Length > stream.Count) {\n        continue;\n    }\n    bool match = true;\n    for (int k = 0; k < word.Length; k++) {\n        int streamIdx = stream.Count - word.Length + k;\n        if (stream[streamIdx] != word[k].ToString()) {\n            match = false;\n        }\n    }\n    if (match) {\n        return true;\n    }\n}\nreturn false;","lineMap":{"2":1,"3":2,"4":3,"5":5,"6":6,"7":7,"8":8,"9":9,"10":12,"11":13,"12":16},"statementBundles":{"4":{"startLine":3,"endLine":4},"9":{"startLine":9,"endLine":11},"11":{"startLine":13,"endLine":15}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"for (string word : words) {\n    if (word.size() > stream.size()) {\n        continue;\n    }\n    bool match = true;\n    for (int k = 0; k < word.size(); k++) {\n        int stream_idx = (stream.size() - word.size()) + k;\n        if (stream[stream_idx] != string(1, word[k])) {\n            match = false;\n        }\n    }\n    if (match) {\n        return true;\n    }\n}\nreturn false;","lineMap":{"2":1,"3":2,"4":3,"5":5,"6":6,"7":7,"8":8,"9":9,"10":12,"11":13,"12":16},"statementBundles":{"4":{"startLine":3,"endLine":4},"9":{"startLine":9,"endLine":11},"11":{"startLine":13,"endLine":15}}}}}},{"id":"cost-probe","kind":"case-probe","chapter":"The slow way","eyebrow":"Count the work","title":"How much does one query read?","workspacePanel":"trace","summary":"There are w stored words, each up to length m, and up to 40000 queries arrive.","options":[{"id":"all-words","label":"Up to every character of every word, about w times m, on each query","rationale":"Nothing records which word might end the stream, so each query tests the tail against all w words, reading up to m characters each. The same w times m work repeats on every one of the up to 40000 letters.","isCorrect":true},{"id":"one-char","label":"Just one character, the new letter, per query","rationale":"A word can be many letters long, so one new letter is not enough to confirm or rule out a match. The scan still has to compare full words against the tail.","isCorrect":false},{"id":"log-words","label":"About log w per query, if the words are kept sorted","rationale":"Sorting helps find a whole word by binary search, but a suffix match is not a whole-stream lookup. The tail can match different words at different lengths, so sorting does not cut the per-query scan.","isCorrect":false}],"answer":"About w times m per query. With words in a flat list, each arriving letter re-tests the stream tail against all of them, reading up to m characters per word. The list carries no reusable matching state from one query to the next, so the same w times m comparisons repeat for every one of the up to 40000 letters."},{"id":"reverse-probe","kind":"case-probe","chapter":"The idea","eyebrow":"Find the structure","title":"Which letter of the stream is shared by every possible match?","workspacePanel":"visualizer","summary":"Stored words have different lengths, but any candidate suffix must line up against the stream's tail. The question is which single position the stream and every possible match are guaranteed to agree on.","options":[{"id":"newest-back","label":"The newest letter, so compare words from their last character backward","rationale":"Any matching suffix ends at the newest letter, so every candidate agrees on that final character first. Compare each word from its last letter back toward its first, and words that end the same way, like \"cd\" and a hypothetical \"ed\", share that comparison. Reverse the stored words and the shared ending becomes one shared path walked from the newest letter.","isCorrect":true},{"id":"oldest-front","label":"The oldest letter, so compare words from their first character forward","rationale":"A suffix ends at the stream tail. The oldest letter shifts out of every window and is shared by nothing, so comparing from the front lines up the wrong ends of the word and the stream.","isCorrect":false},{"id":"middle","label":"The middle letter, since that is where most words overlap","rationale":"Words have different lengths, so they have no common middle. Only the final character is guaranteed to coincide with the stream's newest letter, which is what a suffix match pins down.","isCorrect":false}],"answer":"The newest letter. Every matching suffix ends there, so compare each word from its last character backward. Reversing the stored words turns that backward comparison into a forward walk from the newest letter, and words ending alike share the walk, just like a prefix tree shares openings.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"s","state":{"graph":{"nodes":[{"id":"d","label":"d"},{"id":"dc","label":"c"},{"id":"f","label":"f"},{"id":"l","label":"l"},{"id":"lk","label":"k"}],"edges":[["d","dc"],["l","lk"]],"current":"d","highlighted":["dc"]}}}]}},{"id":"buffer-probe","kind":"case-probe","chapter":"The idea","eyebrow":"Bound the state","title":"How many of the stream's letters can a query ever need?","workspacePanel":"visualizer","summary":"The longest stored word here is \"cd\" or \"kl\", two letters. The stream can grow to 40000 letters.","options":[{"id":"longest-word","label":"Only the recent max_len letters","rationale":"A suffix match can be no longer than the longest stored word, so the walk backward from the newest letter stops once it has stepped that many times. Keeping only the last max-word-length letters of the stream, call it max_len, is enough, and it caps both the memory and the per-query work.","isCorrect":true},{"id":"whole-stream","label":"All of them, so the full stream must be kept","rationale":"Keeping the entire stream wastes memory and time. Any letter older than the longest word can never be part of a match, so the walk would only read characters that cannot reach a word-end mark.","isCorrect":false},{"id":"one-letter","label":"Just the newest letter, since that is where matches end","rationale":"The match ends at the newest letter but can extend several letters back, like \"cd\" needing both c and d. One letter cannot confirm a multi-letter word, so a small buffer of recent letters is required.","isCorrect":false}],"answer":"Only the last max_len letters, where max_len is the longest stored word. A match cannot reach further back than that, so the stream buffer can drop anything older and each query walks at most max_len steps.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"s","state":{"graph":{"nodes":[{"id":"d","label":"d"},{"id":"dc","label":"c"},{"id":"f","label":"f"},{"id":"l","label":"l"},{"id":"lk","label":"k"}],"edges":[["d","dc"],["l","lk"]],"current":"d"}}}]}},{"id":"approach-selection","kind":"choice","source":"approach-selection","chapter":"The idea","eyebrow":"Pick the route","title":"Which structure should hold the words?","workspacePanel":"visualizer","selection":{"contract":"approach-selection-v1","question":"Which implementation should we use?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"scan-all-words","name":"Re-check every word against the stream tail","summary":"On each letter, compare the tail of the stream against every stored word.","decisionReason":"It answers correctly, but it re-reads all w words on every one of the up to 40000 queries, so the same comparisons repeat letter after letter.","complexity":{"time":"O(w * m) per query","space":"O(L)"},"tradeoffs":["It is simple, but every query pays for every word again, even though the words never change."],"isOptimal":false},{"id":"reversed-trie","name":"Reversed-word trie walked from the newest letter","summary":"Insert each word back to front, then on a query walk the trie from the newest stream letter backward, stopping at any word-end mark.","decisionReason":"Reversing the words turns a suffix question into one walk from the newest letter, and words that end alike share that walk, so each query costs only the length of the longest word.","complexity":{"time":"O(L) per query","space":"O(total characters + L)"},"tradeoffs":["It walks at most L steps per query and reuses shared endings, at the cost of building and storing the trie once."],"isOptimal":true}]},"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"s","state":{"graph":{"nodes":[{"id":"d","label":"d"},{"id":"dc","label":"c"},{"id":"f","label":"f"},{"id":"l","label":"l"},{"id":"lk","label":"k"}],"edges":[["d","dc"],["l","lk"]],"visited":["dc","f","lk"]}}}]}},{"id":"reversed-node-state","kind":"case-probe","chapter":"The idea","eyebrow":"Define the nodes","title":"After inserting \"cd\" backward, what does the first edge from root spell?","summary":"The word cd is inserted into the trie from its last letter toward its first.","workspacePanel":"trace","options":[{"id":"d-first","label":"d","rationale":"A suffix ending in cd is checked from the stream tail backward, so the trie path starts with d and then c.","isCorrect":true},{"id":"c-first","label":"c, the first letter in normal reading order","rationale":"Normal order would force the query to know where the suffix starts. The reversed trie starts at the stream tail."},{"id":"whole-word","label":"cd stored as one edge from the root","rationale":"The trie consumes one character per edge so a query can stop after any matched word length."}],"answer":"The first edge is d, because queries walk from the newest stream letter backward."},{"id":"word-end-state","kind":"case-probe","chapter":"The idea","eyebrow":"Mark endings","title":"When can the query return true while walking backward?","summary":"The reversed walk has consumed d then c for the stored word cd.","workspacePanel":"trace","options":[{"id":"word-end","label":"When the current trie node is marked as a word end","rationale":"The path d, c matches cd backward. The word-end mark says that matched suffix is one of the stored words.","isCorrect":true},{"id":"any-node","label":"As soon as the first edge exists","rationale":"For words=[\"cd\"], seeing only d is a prefix of the reversed path. The whole stored word needs d then c."},{"id":"stream-empty","label":"Only after the entire stream has been read","rationale":"A query only needs to read as far as the longest stored word, and can stop when a word-end mark is reached."}],"answer":"The query returns true when the reversed walk reaches a node marked as a stored word end."},{"id":"dry-run-setup","kind":"info","chapter":"Trace it","eyebrow":"Watch it move","title":"Reverse the words into the tree, then feed the stream","workspacePanel":"visualizer","body":["Each stored word goes in back to front. \"cd\" becomes the path d then c and the c node is marked as a word end; \"f\" is a single d-less path of one node, marked; \"kl\" becomes l then k, marked at k. Words that end the same way would share their first reversed steps, just as the tree below already separates the three endings d, f, l at the root.","Now the letters a, b, c, d arrive in turn. After each one you will walk from the newest letter backward through this tree and watch where a word end is reached."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"s","state":{"graph":{"nodes":[{"id":"d","label":"d"},{"id":"dc","label":"c"},{"id":"f","label":"f"},{"id":"l","label":"l"},{"id":"lk","label":"k"}],"edges":[["d","dc"],["l","lk"]],"highlighted":["dc","f","lk"]}}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","chapter":"Trace it","eyebrow":"Trace the walk","title":"Feed a, b, c, d and watch \"cd\" surface","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"walk-b","state":{"graph":{"nodes":[{"id":"d","label":"d"},{"id":"dc","label":"c"},{"id":"f","label":"f"},{"id":"l","label":"l"},{"id":"lk","label":"k"}],"edges":[["d","dc"],["l","lk"]]}}},{"id":"walk-c","state":{"graph":{"nodes":[{"id":"d","label":"d"},{"id":"dc","label":"c"},{"id":"f","label":"f"},{"id":"l","label":"l"},{"id":"lk","label":"k"}],"edges":[["d","dc"],["l","lk"]]}}},{"id":"walk-d","state":{"graph":{"nodes":[{"id":"d","label":"d"},{"id":"dc","label":"c"},{"id":"f","label":"f"},{"id":"l","label":"l"},{"id":"lk","label":"k"}],"edges":[["d","dc"],["l","lk"]],"current":"d","highlighted":["dc"],"activeEdges":[["d","dc"]]}}},{"id":"match-cd","state":{"graph":{"nodes":[{"id":"d","label":"d"},{"id":"dc","label":"c"},{"id":"f","label":"f"},{"id":"l","label":"l"},{"id":"lk","label":"k"}],"edges":[["d","dc"],["l","lk"]],"current":"dc","highlighted":["d"],"visited":["dc"],"activeEdges":[["d","dc"]]}}}]},"beats":[{"id":"walk-b","title":"After b arrives, the walk starts at the newest letter. What does it find?","summary":"The stream is \"ab\". The walk begins at the root and takes the newest letter, b, as its first step.","prompt":"The newest letter is b. The walk looks for a b child of the root.","options":[{"id":"miss","label":"No child for b at the root, so the query stops and returns false","rationale":"No stored word ends in b, so the root has no b child. The walk needs the newest letter to match a first reversed step, and it does not, so the query returns false at once without reading older letters.","isCorrect":true},{"id":"keep-going","label":"Skip b and try the older letter a instead","rationale":"The newest letter is the anchor of any suffix match, so it cannot be skipped. If b has no child, no suffix ending in b can be a word, and the query is already done.","isCorrect":false},{"id":"true","label":"Return true, because b is a single letter in the stream","rationale":"A single letter only matches if that letter is a stored word, and none of \"cd\", \"f\", \"kl\" is b. The missing child is exactly how the tree reports that.","isCorrect":false}],"answer":"The root has no b child, so the query returns false immediately. The newest letter is the first reversed step, and when it has no match no suffix ending there can be a stored word."},{"id":"walk-c","title":"After c arrives, does the stream tail reach a word end?","summary":"The stream is \"abc\". The walk takes the newest letter c as its first step from the root.","prompt":"The newest letter is c. The walk looks for a c child of the root.","options":[{"id":"miss","label":"Return false for this letter","rationale":"No stored word ends in c, so the root has no c child and the walk stops. \"cd\" ends in d, not c, so a stream ending in c cannot complete it yet.","isCorrect":true},{"id":"partial","label":"True, because c is the start of the reversed \"cd\" path","rationale":"The reversed path for \"cd\" is d then c, so c is the second step, reached only after d. Starting from c at the root looks for a word ending in c, and there is none.","isCorrect":false},{"id":"wait","label":"It pauses and waits for the next letter before answering","rationale":"Every query must answer now. The walk from c finds no root child and returns false for this letter; the next letter starts its own fresh walk.","isCorrect":false}],"answer":"False. The root has no c child, because no stored word ends in c. \"cd\" ends in d, so the tree is right to wait until a d arrives at the newest position."},{"id":"walk-d","title":"After d arrives, what does the first step off the root do?","summary":"The stream is \"abcd\". The newest letter is d, and the walk takes it as the first step from the root.","prompt":"The newest letter is d. The next older letter waiting in the stream is c.","options":[{"id":"step-in","label":"Follow d and keep walking","rationale":"The newest letter d matches the root's d child, so the walk steps in. The d node is not marked, since no stored word is just \"d\", so the walk reads the next older letter, c, to see whether the path continues.","isCorrect":true},{"id":"match-now","label":"Return true, because d is a child of the root","rationale":"Reaching a node only proves the letters so far were passed through. The d node carries no word-end mark, so \"d\" alone is not a stored word; the walk must continue to the next letter.","isCorrect":false},{"id":"stop-false","label":"Return false, because d is not a complete word on its own","rationale":"A missing mark on d does not end the query, because longer words run through d. The walk keeps going to the older letter c instead of giving up.","isCorrect":false}],"answer":"Step into the d node. It matches the newest letter but carries no word-end mark, so the walk reads the next older letter, c, and follows the d node's child for it."},{"id":"match-cd","title":"Reading the older letter c, where does the walk land?","summary":"The walk is on the d node and takes the next older stream letter, c, as its next step.","prompt":"The path walked so far is d, then the step for c. The current node is the d node.","options":[{"id":"true","label":"On the marked c node, so the query returns true for the suffix \"cd\"","rationale":"The c child of d exists and carries a word-end mark, because \"cd\" was inserted reversed as d then c. Walking the newest two letters backward, d then c, reaches that mark, so the suffix \"cd\" of \"abcd\" is a stored word and the query returns true.","isCorrect":true},{"id":"keep-going","label":"Past c to read the even older letter b","rationale":"Once a word-end mark is reached the query can answer true right away; it does not need to consume the rest of the stream. The mark on the c node is the stop condition.","isCorrect":false},{"id":"false","label":"On c, but returns false because c is not the newest letter","rationale":"The walk deliberately reads from newest to oldest, so reaching c as a later step is expected. The mark on c, reached by the path d then c, is exactly the match for \"cd\".","isCorrect":false}],"answer":"On the marked c node. The path d then c spells \"cd\" reversed and ends on a word-end mark, so the suffix \"cd\" of the stream is a stored word and the query returns true."}]},{"id":"direction-pitfall","kind":"pitfall","chapter":"Trace it","eyebrow":"Spot the trap","title":"Is reaching a trie node enough to answer true?","workspacePanel":"trace","summary":"Walking newest-letter-first is right, but the stop rule is easy to get wrong. It looks tempting to answer true the moment the walk can take a step into the tree. Watch it judge words=[\"cd\"] with the stream just \"d\".","pitfall":"The loop below walks in the correct backward order, but it reports a match as soon as it steps into any child node, without checking whether that node marks the end of a stored word.","whyItMatters":"With only \"cd\" stored, the reversed path is d then c, and the word-end mark sits on the c node. The d node only records a partial path. For the stream \"d\", the newest letter d does have a child off the root, so this version steps in and immediately returns true, claiming \"d\" is a stored word. But \"d\" is not stored; only the full suffix \"cd\" should match. Stepping into a node only proves the letters so far form a prefix of some reversed word. The query must return true only when it lands on a node carrying a word-end mark.","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 query(root: TrieNode, stream: list[str]) -> bool:\n    node = root\n    for ch in reversed(stream):\n        if ch not in node.children:\n            return False\n        node = node.children[ch]\n        if node:\n            return True\n    return False","steps":[{"id":"p-feed-d","title":"It feeds the newest letter d first","codeLine":11,"summary":"Stream is \"d\". Walking newest-first, the first letter handed to the tree is d. The root has a d child, the reversed first step of \"cd\", so the walk steps into the d node.","state":{"graph":{"nodes":[{"id":"d","label":"d"},{"id":"dc","label":"c"}],"edges":[["d","dc"]],"current":"d"}}},{"id":"p-early-true","title":"It returns true just for reaching the d node","codeLine":12,"summary":"The d node exists, so this version answers true right here, even though the d node carries no word-end mark. The word-end mark for \"cd\" sits one step further on, at the c node.","state":{"graph":{"nodes":[{"id":"d","label":"d"},{"id":"dc","label":"c"}],"edges":[["d","dc"]],"current":"d","highlighted":["d"]}}},{"id":"p-wrong","title":"But \"d\" is not a stored word","codeLine":13,"summary":"It returns true, yet the only stored word is \"cd\" and the stream \"d\" has no suffix equal to it, so the answer should be false. The real word-end mark sits one step further on, at the c node the walk never reached. The missing word-end check is what made it wrongly say true.","state":{"graph":{"nodes":[{"id":"d","label":"d"},{"id":"dc","label":"c"}],"edges":[["d","dc"]],"current":"d","highlighted":["dc"],"activeEdges":[["d","dc"]]}}}],"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\nlet node = root;\nfor (const ch of [...stream].reverse()) {\n    if (!node.children.has(ch)) {\n        return false;\n    }\n    node = node.children.get(ch);\n    if (node != null) {\n        return true;\n    }\n}\nreturn false;","lineMap":{"3":3,"4":4,"7":8,"8":9,"9":10,"10":11,"11":13,"12":14,"13":15,"14":18},"statementBundles":{"4":{"startLine":4,"endLine":6},"10":{"startLine":11,"endLine":12},"13":{"startLine":15,"endLine":17}},"alternateStyles":{"close-to-source":{"code":"class TrieNode {\n    constructor() {\n        this.children = new Map();\n        this.isEnd = false;\n    }\n}\n\nlet node = root;\nfor (const ch of [...stream].reverse()) {\n    if (!node.children.has(ch)) {\n        return false;\n    }\n    const nodeValue = node.children.get(ch);\n    if (nodeValue === undefined) throw new Error(\"KeyError\");\n    node = nodeValue;\n    if (node != null) {\n        return true;\n    }\n}\nreturn false;","lineMap":{"3":3,"4":4,"7":8,"8":9,"9":10,"10":11,"11":13,"12":16,"13":17,"14":20},"statementBundles":{"4":{"startLine":4,"endLine":6},"10":{"startLine":11,"endLine":12},"11":{"startLine":13,"endLine":15},"13":{"startLine":17,"endLine":19}}}}},"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\nlet node = root;\nfor (const ch of [...stream].reverse()) {\n    if (!node.children.has(ch)) {\n        return false;\n    }\n    node = node.children.get(ch)!;\n    if (node != null) {\n        return true;\n    }\n}\nreturn false;","lineMap":{"3":6,"4":7,"7":11,"8":12,"9":13,"10":14,"11":16,"12":17,"13":18,"14":21},"statementBundles":{"4":{"startLine":7,"endLine":9},"10":{"startLine":14,"endLine":15},"13":{"startLine":18,"endLine":20}},"alternateStyles":{"close-to-source":{"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\nlet node = root;\nfor (const ch of [...stream].reverse()) {\n    if (!node.children.has(ch)) {\n        return false;\n    }\n    const nodeValue = node.children.get(ch);\n    if (nodeValue === undefined) throw new Error(\"KeyError\");\n    node = nodeValue;\n    if (node != null) {\n        return true;\n    }\n}\nreturn false;","lineMap":{"3":6,"4":7,"7":11,"8":12,"9":13,"10":14,"11":16,"12":19,"13":20,"14":23},"statementBundles":{"4":{"startLine":7,"endLine":9},"10":{"startLine":14,"endLine":15},"11":{"startLine":16,"endLine":18},"13":{"startLine":20,"endLine":22}}}}},"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\nTrieNode node = root;\nfor (ListIterator<String> chIterator = stream.listIterator(stream.size()); chIterator.hasPrevious();) {\n    String ch = chIterator.previous();\n    if (!node.children.containsKey(ch)) {\n        return false;\n    }\n    node = node.children.get(ch);\n    if (node != null) {\n        return true;\n    }\n}","lineMap":{"3":6,"4":7,"7":11,"8":12,"9":14,"10":15,"11":17,"12":18,"13":19},"statementBundles":{"4":{"startLine":7,"endLine":9},"8":{"startLine":12,"endLine":13},"10":{"startLine":15,"endLine":16},"13":{"startLine":19,"endLine":21}},"alternateStyles":{"close-to-source":{"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\nTrieNode node = root;\nfor (ListIterator<String> chIterator = stream.listIterator(stream.size()); chIterator.hasPrevious();) {\n    String ch = chIterator.previous();\n    if (!node.children.containsKey(ch)) {\n        return false;\n    }\n    node = requireMapValue(node.children, ch);\n    if (node != null) {\n        return true;\n    }\n}","lineMap":{"3":6,"4":7,"7":11,"8":12,"9":14,"10":15,"11":17,"12":18,"13":19},"statementBundles":{"4":{"startLine":7,"endLine":9},"8":{"startLine":12,"endLine":13},"10":{"startLine":15,"endLine":16},"13":{"startLine":19,"endLine":21}}}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"public class TraceCodeRuntime\n{\n    protected\n\n}\n\npublic class TrieNode : TraceCodeRuntime\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\npublic class Solution : TraceCodeRuntime\n{\n\n    TrieNode node = root;\n    foreach (string ch in Reversed(stream)) {\n        if (!node.children.ContainsKey(ch)) {\n            return false;\n        }\n        node = node.children[ch];\n        if (node != null) {\n            return true;\n        }\n    }\n    return false;\n\n}","lineMap":{"3":14,"4":15,"7":22,"8":23,"9":24,"10":25,"11":27,"12":28,"13":29,"14":32},"statementBundles":{"4":{"startLine":15,"endLine":20},"10":{"startLine":25,"endLine":26},"13":{"startLine":29,"endLine":31},"14":{"startLine":32,"endLine":34}}},"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\nTrieNode* node = root;\nvector<string> ch_values = stream;\nreverse(ch_values.begin(), ch_values.end());\nfor (string ch : ch_values) {\n    if (!node->children.count(ch)) {\n        return false;\n    }\n    node = node->children.at(ch);\n    if (node) {\n        return true;\n    }\n}\nreturn false;","lineMap":{"3":6,"4":7,"7":11,"8":12,"9":15,"10":16,"11":18,"12":19,"13":20,"14":23},"statementBundles":{"4":{"startLine":7,"endLine":9},"8":{"startLine":12,"endLine":14},"10":{"startLine":16,"endLine":17},"13":{"startLine":20,"endLine":22}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Where does the word-end check have to fire?","workspacePanel":"visualizer","body":["The walk runs from the newest letter backward through the reversed trie. When exactly it should report a match, and how far back it should ever read, are the two things the query has to get right.","Two inputs put those under pressure: a one-letter stored word, and a stream much longer than any stored word. Decide what the query must do in each."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"s","state":{"graph":{"nodes":[{"id":"d","label":"d"},{"id":"dc","label":"c"},{"id":"f","label":"f"},{"id":"l","label":"l"},{"id":"lk","label":"k"}],"edges":[["d","dc"],["l","lk"]],"visited":["dc","f","lk"]}}}]}},{"id":"single-letter-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"With \"f\" stored, when must query notice the match?","workspacePanel":"visualizer","summary":"The stored words include the one-letter word \"f\", and the latest query letter is f.","options":[{"id":"after-each","label":"Immediately on the f node","rationale":"The match for \"f\" is complete after a single step onto the f node. If the query only checked the word-end mark after walking max_len letters, it would step past this one-letter match. Reading the mark after each step is what lets a short word match as soon as its last letter arrives.","isCorrect":true},{"id":"at-end","label":"Only after the walk has consumed max_len letters","rationale":"Waiting until the end would skip the f match, which is done after one step. Different words end at different depths, so the mark has to be checked at every node the walk reaches.","isCorrect":false},{"id":"never-short","label":"It cannot match, because one letter is too short to walk","rationale":"One letter is a full walk of one step. The f node exists and is marked, so a stream ending in f matches immediately; short words are not a problem, they just match early.","isCorrect":false}],"answer":"Right after the first step. The f node is a word end, so the match completes immediately. Because words end at different depths, the query checks the word-end mark after every step it takes, which is how a one-letter word matches the moment its letter arrives.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"s","state":{"graph":{"nodes":[{"id":"d","label":"d"},{"id":"dc","label":"c"},{"id":"f","label":"f"},{"id":"l","label":"l"},{"id":"lk","label":"k"}],"edges":[["d","dc"],["l","lk"]],"current":"f"}}}]}},{"id":"long-stream-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"After 40000 letters, how far back should a query read?","workspacePanel":"visualizer","summary":"The longest stored word is two letters, and the stream has grown to tens of thousands of letters.","options":[{"id":"cap","label":"At most the last max_len letters, so the buffer drops anything older","rationale":"No suffix longer than the longest word can match, so reading past max_len letters back only wastes work. Capping the stored stream to its last max_len letters keeps each query at a few steps and the memory bounded, no matter how many letters have arrived.","isCorrect":true},{"id":"all","label":"All 40000 letters, to be safe","rationale":"Letters older than the longest word can never reach a word-end mark, because the walk would run out of matching children first. Keeping them all grows memory without ever changing an answer.","isCorrect":false},{"id":"double","label":"Twice max_len, to leave a margin","rationale":"There is no match longer than max_len, so a margin reads letters that no stored word can use. Exactly max_len recent letters is both necessary and sufficient.","isCorrect":false}],"answer":"At most the last max_len letters. A match can reach no further back than the longest word, so the buffer keeps only that many recent letters and discards older ones, which bounds both memory and per-query work even after 40000 letters.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"s","state":{"graph":{"nodes":[{"id":"d","label":"d"},{"id":"dc","label":"c"},{"id":"f","label":"f"},{"id":"l","label":"l"},{"id":"lk","label":"k"}],"edges":[["d","dc"],["l","lk"]],"current":"d"}}}]}},{"id":"ready-to-code","kind":"info","chapter":"Code","eyebrow":"Get ready to code","title":"Turn the reversed walk into code","workspacePanel":"visualizer","summary":"Build the trie back to front, then read the stream from newest to oldest.","body":["Give each node a small map from character to child and a word-end mark, and keep one empty root. Build the trie once by inserting each word back to front, marking the node its last reversed step ends on, and track max_len as the longest word seen.","On a query, append the letter and trim the stored stream to its last max_len letters. Then walk from the newest letter backward: follow a child when it exists, turn back the moment one is missing, and after each step report a match if the node is a word end."],"ctaLabel":"Start coding","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"s","state":{"graph":{"nodes":[{"id":"d","label":"d"},{"id":"dc","label":"c"},{"id":"f","label":"f"},{"id":"l","label":"l"},{"id":"lk","label":"k"}],"edges":[["d","dc"],["l","lk"]],"visited":["dc","f","lk"]}}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","eyebrow":"Code the rule","title":"Build the reversed trie checker","summary":"Follow the trie and stream moves in order.","workspacePanel":"code","checkpoints":[{"id":"node-class","title":"Create trie nodes","description":"Give each node child links and a terminal marker.","commonMistakes":["Storing only one child","Forgetting the terminal marker"],"hint":"Each node needs a map from character to child and a boolean for word endings.","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 children or word endings.","roles":["trie node","children","terminal marker"],"mustProve":["Trie node state includes child storage and terminal state."],"mustNotAccept":["Flat word lists without trie nodes."],"equivalentVariants":["Use dictionaries, maps, or arrays for child links."]},"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 root and stream","description":"Create the trie root and the bounded stream buffer.","commonMistakes":["Building a new root on every query","Not keeping recent stream letters"],"hint":"The constructor owns both the root node and the stream state.","semanticSpec":{"intent":"Initialize persistent trie root state.","doneWhen":"The constructor stores a root trie node.","shouldFailWhen":"This step should fail if the query cannot start from a persistent trie root.","roles":["trie root","stream buffer"],"mustProve":["A persistent trie root is initialized by the class constructor."],"mustNotAccept":["Creating only local roots inside query."],"equivalentVariants":["Use root, head, or another persistent field for the trie root."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"initializes_trie_root","scope":"trie-class","readMode":"tree-trie-value-query-v1"}]}},{"id":"insert-reversed-words","title":"Insert reversed words","description":"Walk each word from back to front and mark its terminal trie node.","commonMistakes":["Inserting words in the original direction","Forgetting to mark complete words"],"hint":"A stream suffix should line up with a forward walk from the newest letter.","semanticSpec":{"intent":"Insert stored words as trie paths.","doneWhen":"The constructor creates missing trie nodes while scanning word characters and marks terminal nodes.","shouldFailWhen":"This step should fail if words are only kept in a flat list.","roles":["word","trie path","terminal marker"],"mustProve":["Words are represented as trie paths with terminal markers."],"mustNotAccept":["Checking every word directly on each query."],"equivalentVariants":["Reverse each word first or iterate its characters from right to left."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"inserts_trie_word","scope":"insert-method","readMode":"tree-trie-value-query-v1"}]}},{"id":"query-suffix-path","title":"Walk query suffix","description":"After adding a letter, walk backward through the stream using trie child links.","commonMistakes":["Walking from the oldest stream letter","Continuing after a missing child"],"hint":"The newest character is the first trie step.","semanticSpec":{"intent":"Use trie child links to test stream suffixes.","doneWhen":"query follows trie links through recent stream characters and stops on missing paths.","shouldFailWhen":"This step should fail if query does not traverse trie child links.","roles":["stream character","current trie node","child link"],"mustProve":["Query advances through trie child links based on the stream."],"mustNotAccept":["Scanning stored words without trie traversal."],"equivalentVariants":["Store the stream as a list, string, deque, or capped buffer."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"checks_trie_prefix","scope":"startswith-method","readMode":"tree-trie-value-query-v1"}]}},{"id":"trie-workflow","title":"Complete trie workflow","description":"Combine reversed insertion with suffix queries that return when a terminal node is reached.","commonMistakes":["Returning true for any prefix instead of a complete word","Never checking terminal markers during query"],"hint":"A query matches only when a walked trie node marks the end of a stored word.","semanticSpec":{"intent":"Assemble the full trie-backed stream-checking workflow.","doneWhen":"The solution initializes trie state, inserts words, and queries through trie links.","shouldFailWhen":"This step should fail if the trie pieces are not connected into one workflow.","roles":["reversed trie","stream query","terminal marker"],"mustProve":["The solution has a coherent trie workflow."],"mustNotAccept":["Independent code fragments that do not form a working trie checker."],"equivalentVariants":["Use helper methods or build the trie directly in the constructor."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"workflow","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":"Reversing the words turns a suffix question into one shared walk from the newest letter.","body":["A suffix match always ends at the newest letter, so storing each word back to front lets every query walk from that letter backward, and words ending alike share the early steps the way a prefix tree shares openings.","A word-end mark, read after each step, says when a stored word has just been completed, and capping the stream to the longest word keeps the walk short."],"takeaways":[{"title":"Reversed words make suffixes into prefixes","body":"Because a match ends at the newest letter, inserting each word back to front lets one backward walk test every candidate at once, instead of re-checking all w words per query."},{"title":"The walk goes newest letter first","body":"The query reads the stream from its newest letter toward older ones, since that newest letter is the anchor every suffix match shares, which is why walking front to back misses real matches."},{"title":"Bounded work per query","body":"Keeping only the last max_len letters and stopping at the first word-end mark makes each query cost O(L) in the longest word, down from the flat list's O(w times m), even across 40000 letters."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"},"starterFunctionName":"StreamChecker","tags":["Trie","Design","Stream"]}
