{"id":"trie-counter","title":"Trie Counter","difficulty":"medium","patterns":["trie"],"primaryConcept":"trie-basics","concepts":["trie-basics"],"problemForm":"application","companies":["Google","Amazon","Meta","Microsoft"],"category":"trees-graphs","executionStyle":"ops-class","compareMode":"exact","syntheticTestConfig":{"inputShape":"operations","primaryParam":"operations","secondaryParam":"arguments","sizeMetric":"op-count","opVocabulary":[{"name":"TrieCounter","arity":0,"weight":1},{"name":"insert","arity":1,"argTypes":["string"],"weight":4},{"name":"search","arity":1,"argTypes":["string"],"weight":2},{"name":"startsWith","arity":1,"argTypes":["string"],"weight":2},{"name":"countWordsEqualTo","arity":1,"argTypes":["string"],"weight":3},{"name":"countWordsStartingWith","arity":1,"argTypes":["string"],"weight":3},{"name":"erase","arity":1,"argTypes":["string"],"weight":1}]},"description":"Design a `TrieCounter` class that stores lowercase words and supports prefix-aware counting.\n\nImplement:\n- `insert(word)`: add one occurrence of `word`\n- `search(word)`: return whether `word` currently exists at least once\n- `startsWith(prefix)`: return whether any stored word has `prefix`\n- `countWordsEqualTo(word)`: return how many stored occurrences equal `word`\n- `countWordsStartingWith(prefix)`: return how many stored occurrences start with `prefix`\n- `erase(word)`: remove one occurrence if it exists","examples":[{"input":"operations = [\"TrieCounter\",\"insert\",\"insert\",\"countWordsEqualTo\",\"countWordsStartingWith\",\"erase\",\"countWordsEqualTo\"]\narguments = [[],[\"apple\"],[\"apple\"],[\"apple\"],[\"app\"],[\"apple\"],[\"apple\"]]","output":"[null,null,null,2,2,null,1]","explanation":"Two copies of apple are inserted, then one copy is erased."},{"input":"operations = [\"TrieCounter\",\"insert\",\"insert\",\"search\",\"startsWith\",\"erase\",\"search\"]\narguments = [[],[\"app\"],[\"apple\"],[\"app\"],[\"ap\"],[\"app\"],[\"app\"]]","output":"[null,null,null,true,true,null,false]","explanation":"After erasing app, apple still keeps the prefix ap alive but app is no longer a complete stored word."}],"constraints":[{"id":"1-len-word-len-prefix-50","text":"1 <= len(word), len(prefix) <= 50"},{"id":"word-and-prefix-consist-only-of-lowercase-english-letters","text":"word and prefix consist only of lowercase English letters"},{"id":"at-most-1000-operations-will-be-called","text":"At most 1000 operations will be called"}],"starterCode":"class TrieNode:\n    def __init__(self):\n        self.children = {}\n        self.is_end = False\n        self.word_count = 0\n        self.prefix_count = 0\n\nclass TrieCounter:\n    def __init__(self):\n        # Your code here\n        pass\n\n    def insert(self, word: str) -> None:\n        # Your code here\n        pass\n\n    def search(self, word: str) -> bool:\n        # Your code here\n        pass\n\n    def startsWith(self, prefix: str) -> bool:\n        # Your code here\n        pass\n\n    def countWordsEqualTo(self, word: str) -> int:\n        # Your code here\n        pass\n\n    def countWordsStartingWith(self, prefix: str) -> int:\n        # Your code here\n        pass\n\n    def erase(self, word: str) -> None:\n        # Your code here\n        pass","functionName":"TrieCounter","testCases":[{"id":"1","input":{"operations":["TrieCounter","insert","insert","countWordsEqualTo","countWordsStartingWith","erase","countWordsEqualTo","countWordsStartingWith"],"arguments":[[],["apple"],["apple"],["apple"],["app"],["apple"],["apple"],["app"]]},"expected":[null,null,null,2,2,null,1,1],"description":"Duplicate word counts decrement after erase."},{"id":"2","input":{"operations":["TrieCounter","insert","insert","search","startsWith","erase","search","startsWith"],"arguments":[[],["app"],["apple"],["app"],["ap"],["app"],["app"],["ap"]]},"expected":[null,null,null,true,true,null,false,true],"description":"Erasing a word does not remove longer words with the same prefix."},{"id":"3","input":{"operations":["TrieCounter","insert","insert","insert","countWordsStartingWith","countWordsEqualTo"],"arguments":[[],["trace"],["trie"],["tree"],["tr"],["try"]]},"expected":[null,null,null,null,3,0],"description":"Shared prefix counts all descendants."},{"id":"4","input":{"operations":["TrieCounter","erase","insert","erase","countWordsEqualTo"],"arguments":[[],["ghost"],["ghost"],["ghost"],["ghost"]]},"expected":[null,null,null,null,0],"description":"Erasing a missing word is a no-op."},{"id":"h1","input":{"operations":["TrieCounter","insert","insert","insert","erase","countWordsEqualTo","countWordsStartingWith"],"arguments":[[],["a"],["a"],["ab"],["a"],["a"],["a"]]},"expected":[null,null,null,null,null,1,2],"description":"Single-letter word is also a prefix of another word."},{"id":"h2","input":{"operations":["TrieCounter","insert","startsWith","search","countWordsStartingWith"],"arguments":[[],["code"],["coder"],["cod"],["coder"]]},"expected":[null,null,false,false,0],"description":"Longer missing prefix does not exist."},{"id":"h3","input":{"operations":["TrieCounter","insert","insert","insert","countWordsStartingWith","erase","search","countWordsStartingWith","countWordsStartingWith"],"arguments":[[],["car"],["cat"],["cart"],["car"],["car"],["car"],["car"],["ca"]]},"expected":[null,null,null,null,2,null,false,1,2],"description":"Erasing an exact word leaves longer words with the same prefix."},{"id":"h4","input":{"operations":["TrieCounter","insert","erase","search","startsWith","countWordsEqualTo","countWordsStartingWith"],"arguments":[[],["dog"],["do"],["dog"],["do"],["do"],["do"]]},"expected":[null,null,null,true,true,0,1],"description":"Erasing a missing prefix-shaped word does not disturb a longer word."},{"id":"h5","input":{"operations":["TrieCounter","insert","insert","insert","erase","erase","countWordsEqualTo","startsWith","erase","search","startsWith","countWordsStartingWith"],"arguments":[[],["a"],["a"],["a"],["a"],["a"],["a"],["a"],["a"],["a"],["a"],["a"]]},"expected":[null,null,null,null,null,null,1,true,null,false,false,0],"description":"Repeated erases eventually clear the final single-letter word."},{"id":"h6","input":{"operations":["TrieCounter","insert","insert","insert","countWordsStartingWith","countWordsStartingWith","search","startsWith"],"arguments":[[],["alpha"],["alps"],["beta"],["al"],["b"],["alp"],["alp"]]},"expected":[null,null,null,null,2,1,false,true],"description":"Branching prefixes support counts and prefix membership separately from exact words."},{"id":"topup-erase-one-of-many","input":{"operations":["TrieCounter","insert","insert","insert","countWordsEqualTo","erase","countWordsEqualTo","countWordsStartingWith"],"arguments":[[],["cat"],["cat"],["car"],["cat"],["cat"],["cat"],["ca"]]},"description":"Erasing one duplicate leaves one exact word and preserves prefix counts.","expected":[null,null,null,null,2,null,1,2]},{"id":"topup-prefix-after-erase","input":{"operations":["TrieCounter","insert","insert","erase","startsWith","search","countWordsStartingWith"],"arguments":[[],["dog"],["dot"],["dog"],["do"],["dog"],["do"]]},"description":"Erasing one branch keeps the shared prefix alive through another word.","expected":[null,null,null,null,true,false,1]}],"hints":[{"level":1,"content":"Each trie node needs child links plus counters for complete words and prefixes passing through it."},{"level":2,"content":"During insertion, increment the prefix counter after moving into each character node."},{"level":3,"content":"Erase should first confirm the word exists, then decrement prefix counters along its path."}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which implementation should we use?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"flat-list","name":"Store all words in a list","summary":"Scan every stored word for exact and prefix counts.","decisionReason":"Every prefix count rereads all N stored words, up to L characters each, even when nothing changed since the last call.","complexity":{"time":"O(N*L) per query","space":"O(N*L)"},"tradeoffs":["Runs in O(N*L) per query time and uses O(N*L) space."],"isOptimal":false},{"id":"trie-counters","name":"Trie with counters","summary":"Walk one character per operation and maintain word and prefix counters.","decisionReason":"A query walks only the L characters of its argument and reads one counter on the node it reaches, instead of touching every stored word.","complexity":{"time":"O(L) per operation","space":"O(T)"},"tradeoffs":["Runs in O(L) per operation time and uses O(T) space."],"isOptimal":true}]},"operationCoverage":"public-methods-v1","codingCheckpoints":[{"id":"node-class","title":"Create counting trie nodes","description":"Give each node child storage plus separate zeroed counters for words passing through and words ending there.","commonMistakes":["Only storing raw words","Mixing prefix and exact counts into one value"],"hint":"Separate child links from terminal and prefix metadata.","semanticSpec":{"intent":"Initialize the two distinct counting roles on every trie node.","doneWhen":"A node initializes child-link storage and at least two independent numeric counters.","shouldFailWhen":"This step should fail if the node has only one counter or no counting state.","roles":["trie node","children","prefix count","exact-word count"],"mustProve":["Two independent numeric counter fields are initialized with the trie node state."],"mustNotAccept":["A node with only one number for both exact and prefix answers."],"equivalentVariants":["Choose any field names for the two numeric roles."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"initializes_trie_counter_node_state","scope":"counter-node-class","readMode":"tree-trie-value-query-v1"}]}},{"id":"trie-root","title":"Initialize root","description":"Create the persistent root node for all operations.","commonMistakes":["Creating a new root per operation","Leaving the root unset"],"hint":"The constructor should store one root trie node.","semanticSpec":{"intent":"Initialize persistent trie root state.","doneWhen":"The class constructor stores a root trie node.","shouldFailWhen":"This step should fail if operations cannot share a root.","roles":["trie root"],"mustProve":["A persistent trie root is initialized."],"mustNotAccept":["A local root inside only one method."],"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-word","title":"Insert words","description":"Walk the word one character at a time and create any missing child nodes.","commonMistakes":["Storing the whole word without creating a path","Forgetting to create missing child nodes"],"hint":"Every character should advance to a child node, creating it if needed.","semanticSpec":{"intent":"Insert a word into the trie.","operations":["insert"],"doneWhen":"The path walk creates missing trie nodes and reaches the terminal node.","shouldFailWhen":"This step should fail if inserted words are not represented as trie paths.","roles":["trie path","terminal node"],"mustProve":["Words are inserted as trie paths."],"mustNotAccept":["Appending words to a flat list only."],"equivalentVariants":["Use `setdefault`, explicit membership checks, or equivalent child creation."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"creates_trie_child_path_on_insert","scope":"insert-method","readMode":"tree-trie-value-query-v1"}]}},{"id":"insert-prefix-count","title":"Count every node the word passes through","description":"After each character advances to its child, increment that node's pass-through counter once.","commonMistakes":["Incrementing only the final node","Incrementing before advancing and counting the root instead"],"hint":"Each visited child represents one more stored word sharing that prefix.","semanticSpec":{"intent":"Maintain the prefix-count role during insertion.","operations":["insert"],"doneWhen":"Insertion increments one numeric node field at every step of the trie path.","shouldFailWhen":"This step should fail if insertion updates the counter only at the terminal node.","roles":["insert path","prefix count"],"mustProve":["Insertion increments the same counter along the entire path."],"mustNotAccept":["A terminal-only increment."],"equivalentVariants":["Advance through a helper or directly inside the loop."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"increments_trie_prefix_count_on_insert","scope":"insert-prefix-count","readMode":"tree-trie-value-query-v1"}]}},{"id":"insert-exact-count","title":"Count words that end at the terminal node","description":"After the full path is consumed, increment a different counter on the final node once.","commonMistakes":["Reusing the pass-through counter","Setting a boolean that loses duplicate occurrences"],"hint":"Only the final node receives this update, because only one word ending is being added.","semanticSpec":{"intent":"Maintain the exact-word-count role during insertion.","operations":["insert"],"doneWhen":"Insertion increments a second numeric field only after the path walk finishes.","shouldFailWhen":"This step should fail if no terminal counter is incremented or both roles use one field.","roles":["terminal node","exact-word count"],"mustProve":["Insertion increments a distinct terminal counter."],"mustNotAccept":["A boolean terminal marker as the only exact-word state."],"equivalentVariants":["Keep or omit a separate boolean marker in addition to the count."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"increments_trie_exact_count_on_insert","scope":"insert-exact-count","readMode":"tree-trie-value-query-v1"}]}},{"id":"exact-search","title":"Return the exact-word count","description":"Walk the full word, return zero when its path is missing, and otherwise return the counter for words ending at the final node.","commonMistakes":["Returning the pass-through counter","Returning a boolean instead of the number of copies"],"hint":"The final node already separates words that end here from words that merely continue through it.","semanticSpec":{"intent":"Return the exact multiplicity stored at the terminal node.","operations":["countWordsEqualTo"],"doneWhen":"The query returns zero for a missing path and otherwise returns the same terminal counter incremented by insertion.","shouldFailWhen":"This step should fail if the method returns the prefix counter, a boolean, or a constant.","roles":["query word","terminal node","exact-word count"],"mustProve":["Exact queries return the terminal counter maintained by insertion."],"mustNotAccept":["Returning the pass-through counter from the final node."],"equivalentVariants":["Share a traversal helper or walk the path directly."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"returns_trie_exact_count","scope":"exact-count-method","readMode":"tree-trie-value-query-v1"}]}},{"id":"prefix-search","title":"Return the prefix count","description":"Walk the prefix path, return zero when it is missing, and otherwise return the counter incremented at every node during insertion.","commonMistakes":["Returning the exact-word counter","Exploring the subtree instead of reading the stored count"],"hint":"The pass-through counter at the final prefix node already summarizes every stored continuation.","semanticSpec":{"intent":"Return how many stored words pass through the final prefix node.","operations":["countWordsStartingWith"],"doneWhen":"The query returns zero for a missing path and otherwise returns the same per-node counter incremented by insertion.","shouldFailWhen":"This step should fail if the method returns the exact-word counter, a boolean, or a constant.","roles":["prefix","current trie node","prefix count"],"mustProve":["Prefix queries return the path counter maintained by insertion."],"mustNotAccept":["Returning the number of words ending exactly at the prefix node."],"equivalentVariants":["Share a traversal helper or walk the path directly."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"returns_trie_prefix_count","scope":"prefix-count-method","readMode":"tree-trie-value-query-v1"}]}},{"id":"exact-exists","title":"Expose exact-word existence","description":"Walk the full word and report whether at least one copy ends at the final node.","commonMistakes":["Treating a prefix path as an exact word","Ignoring that erase can reduce the exact count to zero"],"hint":"Exact existence follows from whether the terminal word state still represents a stored copy.","semanticSpec":{"intent":"Support the public exact-word existence query.","operations":["search"],"doneWhen":"The method follows trie links and returns terminal word state at the end.","shouldFailWhen":"This step should fail if a prefix is accepted as an exact word.","roles":["query word","terminal node"],"mustProve":["Exact existence uses trie traversal and terminal state."],"mustNotAccept":["Prefix-only lookup."],"equivalentVariants":["Return a terminal marker or derive existence from the exact count."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"searches_exact_trie_word","scope":"search-method","readMode":"tree-trie-value-query-v1"}]}},{"id":"prefix-exists","title":"Expose prefix existence","description":"Walk the prefix and report whether any stored word still passes through its final node.","commonMistakes":["Requiring the prefix itself to be a complete word","Returning true for a path whose count fell to zero"],"hint":"Prefix existence follows from whether the final prefix node still represents at least one stored continuation.","semanticSpec":{"intent":"Support the public prefix-existence query.","operations":["startsWith"],"doneWhen":"The method follows trie child links and succeeds only while the prefix remains represented.","shouldFailWhen":"This step should fail if prefix lookup does not traverse trie links.","roles":["prefix","current trie node"],"mustProve":["Prefix existence uses trie traversal."],"mustNotAccept":["A full scan of every stored word."],"equivalentVariants":["Return a positive prefix-count check or an equivalent path-existence result."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"checks_trie_prefix","scope":"startswith-method","readMode":"tree-trie-value-query-v1"}]}},{"id":"erase-guard","title":"Leave missing words untouched","description":"Before decrementing anything, stop when the exact-word query reports that no copy remains.","commonMistakes":["Checking only whether the prefix path exists","Decrementing first and checking afterward"],"hint":"A word can have a path in the trie while its exact count is zero.","semanticSpec":{"intent":"Guard erase with the exact multiplicity query.","operations":["erase"],"doneWhen":"Erase exits on a zero result from the exact-count workflow before performing counter mutations.","shouldFailWhen":"This step should fail if erasing a missing word can reach the decrement logic.","roles":["erase","exact-word count","early exit"],"mustProve":["The zero exact-count result guards the erase mutations."],"mustNotAccept":["A prefix-existence check that allows deleting an absent exact word."],"equivalentVariants":["Call the exact query directly or a shared helper returning the same count."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"guards_missing_trie_erase","scope":"erase-guard","readMode":"tree-trie-value-query-v1"}]}},{"id":"erase-prefix-count","title":"Remove one pass from every node","description":"Walk the word's path and decrement the same pass-through counter that insertion incremented at each child.","commonMistakes":["Decrementing only the terminal node","Updating a different field from insertion"],"hint":"Erasing one copy reverses exactly one prefix contribution at every character.","semanticSpec":{"intent":"Reverse the per-node prefix-count updates.","operations":["erase"],"doneWhen":"Erase decrements the insertion path counter once at every node on the word path.","shouldFailWhen":"This step should fail if any prefix contribution remains after a valid erase.","roles":["erase path","prefix count"],"mustProve":["Erase decrements the same path counter used by insertion and prefix queries."],"mustNotAccept":["Changing an unrelated numeric field along the path."],"equivalentVariants":["Use a saved path or traverse the children again."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"decrements_trie_prefix_count_on_erase","scope":"erase-prefix-count","readMode":"tree-trie-value-query-v1"}]}},{"id":"erase-exact-count","title":"Remove one exact ending","description":"After reaching the final node, decrement the same terminal counter returned by the exact-word query.","commonMistakes":["Clearing every duplicate at once","Decrementing the pass-through counter twice"],"hint":"One erase reverses one terminal increment, even when other copies remain.","semanticSpec":{"intent":"Reverse the terminal exact-count update.","operations":["erase"],"doneWhen":"Erase decrements the terminal counter maintained by insertion and returned by exact queries.","shouldFailWhen":"This step should fail if the exact multiplicity does not fall by one.","roles":["terminal node","exact-word count"],"mustProve":["Erase decrements the same terminal counter used by insertion and exact queries."],"mustNotAccept":["Resetting a boolean without decrementing the duplicate count."],"equivalentVariants":["Update a terminal counter with any learner-chosen field name."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"decrements_trie_exact_count_on_erase","scope":"erase-exact-count","readMode":"tree-trie-value-query-v1"}]}}],"slides":[{"id":"opener","kind":"info","chapter":"The problem","eyebrow":"Read the problem","title":"Count words, and count prefixes, as words come and go","workspacePanel":"problem","body":["You are building a dictionary of lowercase words that can hold the same word more than once. insert(word) adds one occurrence. erase(word) removes one occurrence if any remain. The two counting questions are the heart of it: countWordsEqualTo(word) returns how many stored occurrences equal that exact word, and countWordsStartingWith(prefix) returns how many stored occurrences begin with that prefix.","Insert \"apple\" twice, then countWordsEqualTo(\"apple\") is 2 and countWordsStartingWith(\"app\") is also 2, because both copies begin with \"app\". Now erase(\"apple\") once: countWordsEqualTo(\"apple\") drops to 1, and countWordsStartingWith(\"app\") drops to 1 with it. Keeping those two counts in step as words are added and removed is the whole job."]},{"id":"brute-force","kind":"code-trace","chapter":"The slow way","eyebrow":"The obvious way","title":"Keep every occurrence in a flat list","summary":"A plain list of the words inserted so far answers every question correctly. Watch what countWordsStartingWith has to read to do it.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"class TrieCounter:\n    def __init__(self) -> None:\n        self.words: list[str] = []\n\n    def countWordsStartingWith(self, prefix: str) -> int:\n        total: int = 0\n        for word in self.words:\n            if word.startswith(prefix):\n                total += 1\n        return total","steps":[{"id":"scan-1","title":"Read the first stored word","codeLine":8,"summary":"words = [\"app\", \"apple\", \"apply\"], prefix = \"app\". To count, the list reads \"app\" character by character and checks it against \"app\".","state":{"s":"app","i":2,"labels":{"s":"word"}}},{"id":"scan-2","title":"Then read the next one","codeLine":7,"summary":"\"app\" matched, but the scan cannot stop: it moves on to \"apple\" and re-reads a, p, p before confirming the match. Nothing said \"app\" and \"apple\" already share an opening.","state":{"s":"apple","i":2,"labels":{"s":"word"}}},{"id":"scan-3","title":"And read the last one too","codeLine":7,"summary":"\"apply\" is read the same way, a, p, p again. Three stored words, every character of each, for one count, and the next count starts the whole pass over.","state":{"s":"apply","i":2,"labels":{"s":"word"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"class TrieCounter {\n    constructor() {\n        this.words = [];\n    }\n\n    countWordsStartingWith(prefix) {\n        let total = 0;\n        for (const word of this.words) {\n            if (word.startsWith(prefix)) {\n                total++;\n            }\n        }\n        return total;\n    }\n}","lineMap":{"3":3,"6":7,"7":8,"8":9,"9":10,"10":13},"statementBundles":{"3":{"startLine":3,"endLine":6},"9":{"startLine":10,"endLine":12},"10":{"startLine":13,"endLine":15}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"class TrieCounter {\n    words: Array<string>;\n\n    constructor() {\n        this.words = [];\n    }\n\n    countWordsStartingWith(prefix: string): number {\n        let total = 0;\n        for (const word of this.words) {\n            if (word.startsWith(prefix)) {\n                total++;\n            }\n        }\n        return total;\n    }\n}","lineMap":{"3":5,"6":9,"7":10,"8":11,"9":12,"10":15},"statementBundles":{"3":{"startLine":5,"endLine":8},"9":{"startLine":12,"endLine":14},"10":{"startLine":15,"endLine":17}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"class TrieCounter {\n    List<String> words;\n\n    public TrieCounter() {\n        this.words = new ArrayList<String>();\n    }\n\n    public int countWordsStartingWith(String prefix) {\n        int total = 0;\n        for (String word : this.words) {\n            if (word.startsWith(prefix)) {\n                total++;\n            }\n        }\n        return total;\n    }\n}","lineMap":{"3":5,"6":9,"7":10,"8":11,"9":12,"10":15},"statementBundles":{"3":{"startLine":5,"endLine":8},"9":{"startLine":12,"endLine":14},"10":{"startLine":15,"endLine":17}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"public class TrieCounter\n{\n    public List<string> words;\n\n    public TrieCounter()\n    {\n        this.words = new List<string>();\n    }\n\n    public int CountWordsStartingWith(string prefix)\n    {\n        int total = 0;\n        foreach (string word in this.words) {\n            if (word.StartsWith(prefix)) {\n                total++;\n            }\n        }\n        return total;\n        return 0;\n    }\n}","lineMap":{"3":7,"6":12,"7":13,"8":14,"9":15,"10":18},"statementBundles":{"3":{"startLine":7,"endLine":11},"9":{"startLine":15,"endLine":17},"10":{"startLine":18,"endLine":21}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"struct TrieCounter {\n    vector<string> words;\n\n    TrieCounter() {\n        this->words = vector<string>{};\n    }\n\n    int count_words_starting_with(string prefix) {\n        int total = 0;\n        for (string word : this->words) {\n            if ((word.rfind(prefix, 0) == 0)) {\n                total++;\n            }\n        }\n        return total;\n    }\n};","lineMap":{"3":5,"6":9,"7":10,"8":11,"9":12,"10":15},"statementBundles":{"3":{"startLine":5,"endLine":8},"9":{"startLine":12,"endLine":14},"10":{"startLine":15,"endLine":17}}}}}},{"id":"cost-probe","kind":"case-probe","chapter":"The slow way","eyebrow":"Count the work","title":"How much does one countWordsStartingWith call read?","workspacePanel":"trace","summary":"The list holds w occurrences, each up to length m. A prefix query is run against that list.","options":[{"id":"all","label":"Up to every character of every stored word, about w times m per call","rationale":"A flat list cannot tell which words begin with the prefix without trying each one, so it re-reads all w occurrences, up to m characters each. Every count pays that full w times m again, even though the stored words never changed since the last call.","isCorrect":true},{"id":"prefix-only","label":"Just the characters of the prefix, once","rationale":"That is the cost we would like, but a flat list cannot reach it. With nothing recording that \"app\" and \"apple\" share an opening, the only way to count is to test the prefix against every stored word.","isCorrect":false},{"id":"log","label":"About log w, by keeping the list sorted","rationale":"Sorting helps locate one exact word, but a prefix can match a whole run of words at once, so you still scan that run. Sorting never gets a prefix count down to reading the prefix alone.","isCorrect":false}],"answer":"About w times m per call. A flat list makes every prefix count test all w stored occurrences, reading up to m characters from each one."},{"id":"pattern-quiz","kind":"choice","source":"pattern-recognition","chapter":"The idea","eyebrow":"Find the structure","title":"What do \"app\" and \"apple\" let you store only once?","workspacePanel":"trace","quiz":{"contract":"pattern-recognition-v1","question":"What do \"app\" and \"apple\" let you store only once?","signalPrompt":"Look at how the words overlap, and at the operations that walk one character at a time.","options":[{"id":"trie","label":"Their shared opening \"app\", as one path from a common start that then continues","signal":"This option matches the shared-prefix structure the operations walk.","rationale":"Both words walk a, p, p from the same start, so \"app\" can be a single shared path. \"apple\" simply continues past it with l, e. Every word becomes a walk from the start, one character per step, and words that begin alike reuse the steps they have in common. That shared structure is a trie.","isCorrect":true},{"id":"hash-set","label":"Nothing extra: a hash set already stores each word once","signal":"This option answers exact membership but misses prefix counting.","rationale":"A set removes duplicate identical words, but it keeps \"app\" and \"apple\" as two unrelated keys. A prefix count would still scan every key, because a set records no overlap between words.","isCorrect":false},{"id":"sorted","label":"Their alphabetical order, so binary search can find them","signal":"This option notices ordering but not shared prefixes.","rationale":"Ordering helps find one whole word, but it does not let \"app\" and \"apple\" share their common opening. A prefix question would still scan a run of similar words instead of walking one shared path.","isCorrect":false},{"id":"heap","label":"Their priority, kept in a heap","signal":"This option tracks ordering by priority, not characters.","rationale":"A heap orders by a priority value and has no notion of character paths or shared prefixes, so it cannot answer prefix questions at all.","isCorrect":false}],"missFeedback":"Look for the opening characters \"app\" and \"apple\" have in common, and for operations that walk a word one letter at a time.","hint":"\"app\" and \"apple\" agree on their first three letters; only after that does \"apple\" keep going."},"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"shared","state":{"nums":["app","apple","apply"],"labels":{"nums":"stored words"}}}]}},{"id":"counter-probe","kind":"case-probe","chapter":"The idea","eyebrow":"Make counts cheap","title":"What can each node hold so a prefix count is read in one walk?","workspacePanel":"visualizer","summary":"\"app\" and \"apple\" are both stored. A query for prefix \"app\" walks to the node at the end of a, p, p.","options":[{"id":"running-count","label":"A running count of how many stored words pass through it, bumped on every insert","rationale":"When a word is inserted, it walks one node per character. Add one to a counter on each node it steps onto, and that counter on the \"app\" node becomes exactly the number of stored words whose path runs through it. countWordsStartingWith(\"app\") then walks to that node and reads one number, no subtree to explore.","isCorrect":true},{"id":"walk-subtree","label":"Nothing extra: walk every node below the prefix and add up the word ends","rationale":"That works but throws away the saving. Summing all word-end marks under \"app\" visits the whole subtree, so a popular prefix costs as much as the flat list did. A count kept on the node turns that walk into a single read.","isCorrect":false},{"id":"store-words","label":"The full list of words that pass through it","rationale":"Storing the words back on the node reintroduces the flat list at every node, wasting space and still needing a scan to count. A single integer that rises and falls with inserts and erases is all the count needs.","isCorrect":false}],"answer":"A running count on each node of how many stored words pass through it, bumped by one on every character of every insert. The \"app\" node's count is then the answer to countWordsStartingWith(\"app\"), read in one walk with no subtree to explore.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"counts","state":{"graph":{"nodes":[{"id":"a","label":"a"},{"id":"ap","label":"p"},{"id":"app","label":"p"},{"id":"appl","label":"l"},{"id":"apple","label":"e"}],"edges":[["a","ap"],["ap","app"],["app","appl"],["appl","apple"]],"current":"app"}}}]}},{"id":"approach-selection","kind":"case-probe","chapter":"The idea","eyebrow":"Separate the answers","title":"At the end of \"app\", why are two counters needed?","summary":"The trie stores \"app\" and \"apple\" once each.","workspacePanel":"visualizer","options":[{"id":"two-counts","label":"Two words pass through the node, but only one word ends there","rationale":"Both \"app\" and \"apple\" traverse the final p of \"app\", so its pass-through count is 2. Only \"app\" stops there, so its end count is 1. One number cannot return both answers.","isCorrect":true},{"id":"both-two","label":"Both counts are 2 because both words share the path","rationale":"Sharing the path makes the prefix count 2, but \"apple\" continues to l and e. It does not contribute to the number of words ending at \"app\"."},{"id":"both-one","label":"Both counts are 1 because \"app\" appears once","rationale":"The exact count is 1, but the prefix count includes every stored word that begins with \"app\". Both \"app\" and \"apple\" contribute to that count."}],"answer":"The node at the end of \"app\" needs a pass-through count of 2 and an end count of 1. The first answers countWordsStartingWith(\"app\"); the second answers countWordsEqualTo(\"app\").","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach","state":{"graph":{"nodes":[{"id":"a","label":"a"},{"id":"ap","label":"p"},{"id":"app","label":"p"},{"id":"appl","label":"l"},{"id":"apple","label":"e"}],"edges":[["a","ap"],["ap","app"],["app","appl"],["appl","apple"]],"current":"app","visited":["app","apple"]}}}]}},{"id":"dry-run-setup","kind":"info","chapter":"Trace it","eyebrow":"Watch it move","title":"Insert a word, share its path, then count and erase","workspacePanel":"visualizer","body":["Each node carries two numbers: how many stored words pass through it, and how many words end exactly there. Insert walks the word one character at a time, adding one to the pass-through count on every node it steps onto, then adds one to the end count on the node it finishes on.","\"app\" is already stored below, its path a, p, p marked with a pass-through count of one. You will insert \"apple\" next, watch the shared \"app\" nodes climb to two, read countWordsStartingWith(\"app\"), then erase \"app\" once and watch the counts come back down."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup","state":{"graph":{"nodes":[{"id":"a","label":"a · 1"},{"id":"ap","label":"p · 1"},{"id":"app","label":"p · 1"}],"edges":[["a","ap"],["ap","app"]],"visited":["app"]}}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","chapter":"Trace it","eyebrow":"Trace the counts","title":"Add \"apple\" beside \"app\", count the prefix, then erase \"app\"","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"insert-apple","state":{"graph":{"nodes":[{"id":"a","label":"a · 2"},{"id":"ap","label":"p · 2"},{"id":"app","label":"p · 2"}],"edges":[["a","ap"],["ap","app"]],"current":"app","highlighted":["a","ap"],"activeEdges":[["ap","app"]]}}},{"id":"finish-apple","state":{"graph":{"nodes":[{"id":"a","label":"a · 2"},{"id":"ap","label":"p · 2"},{"id":"app","label":"p · 2"},{"id":"appl","label":"l · 1"},{"id":"apple","label":"e · 1"}],"edges":[["a","ap"],["ap","app"],["app","appl"],["appl","apple"]],"current":"apple","highlighted":["appl"],"visited":["app"],"activeEdges":[["appl","apple"]]}}},{"id":"count-app","state":{"graph":{"nodes":[{"id":"a","label":"a · 2"},{"id":"ap","label":"p · 2"},{"id":"app","label":"p · 2"},{"id":"appl","label":"l · 1"},{"id":"apple","label":"e · 1"}],"edges":[["a","ap"],["ap","app"],["app","appl"],["appl","apple"]],"current":"app","visited":["a","ap"]}}},{"id":"erase-app","state":{"graph":{"nodes":[{"id":"a","label":"a · 1"},{"id":"ap","label":"p · 1"},{"id":"app","label":"p · 1"},{"id":"appl","label":"l · 1"},{"id":"apple","label":"e · 1"}],"edges":[["a","ap"],["ap","app"],["app","appl"],["appl","apple"]],"current":"app","visited":["a","ap"]}}}]},"beats":[{"id":"insert-apple","title":"Inserting \"apple\", what happens at the shared \"app\" nodes?","summary":"\"app\" is already stored, so the path a, p, p exists.","prompt":"\"apple\" begins a, p, p, then continues with l and e.","options":[{"id":"bump","label":"Reuse the three nodes and add one to each one's pass-through count","rationale":"Insert steps onto a node and bumps its pass-through count, whether the node is new or reused. \"apple\" walks the existing a, p, p and lifts each from one to two, because now two stored words pass through them.","isCorrect":true},{"id":"newpath","label":"Build a fresh a, p, p path so \"apple\" keeps its own counts","rationale":"A second path would duplicate \"app\" and split the count that is supposed to total both words. Insert reuses an existing child whenever the character is present, and counts on the shared nodes climb together.","isCorrect":false},{"id":"endonly","label":"Leave the shared nodes alone and only count at the final \"e\"","rationale":"Counting only at the end would leave the \"app\" node still reading one, so countWordsStartingWith(\"app\") would miss \"apple\". The pass-through count must rise on every node the word steps onto.","isCorrect":false}],"answer":"Reuse the a, p, p nodes and add one to each one's pass-through count, lifting them from one to two. Both stored words now pass through \"app\", and the node's count says so."},{"id":"finish-apple","title":"At the last two characters l and e, what does insert do?","summary":"Past the shared \"app\", no child covers l yet, and e is the last character of \"apple\".","prompt":"The \"app\" node has no l child, and after l comes the final e.","options":[{"id":"create","label":"Create l then e as new nodes, count one passing through each, and add one to the end count on e","rationale":"No child covers l, so insert creates l and then e below it, bumping each new node's pass-through count to one. Because e is the last character, it also adds one to the end count there, which is what countWordsEqualTo(\"apple\") will read.","isCorrect":true},{"id":"markapp","label":"Mark the \"app\" node as the end of \"apple\"","rationale":"\"apple\" does not end at \"app\"; it ends two characters later at e. The end count belongs on the node where the word actually finishes.","isCorrect":false},{"id":"nocount","label":"Create l and e but update only the end count","rationale":"Skipping the pass-through count on l and e would make countWordsStartingWith(\"appl\") wrong. Every node a word steps onto gets its pass-through count bumped, new nodes included.","isCorrect":false}],"answer":"Create l and e as new nodes, bump each one's pass-through count to one, and add one to the end count on e. The \"app\" nodes read two, the l and e nodes read one, and e records that one word ends exactly there."},{"id":"count-app","title":"What does countWordsStartingWith(\"app\") read, and where?","summary":"\"app\" and \"apple\" are both stored after the two inserts above.","prompt":"countWordsStartingWith(\"app\") walks a, p, p and lands on the \"app\" node.","options":[{"id":"read-two","label":"It reads the pass-through count on the \"app\" node, which is 2","rationale":"The count was bumped once for \"app\" and once for \"apple\" as each walked through this node, so it reads exactly two. No subtree walk is needed: the single number on the node is the answer.","isCorrect":true},{"id":"end-one","label":"It reads the end count on the \"app\" node, which is 1","rationale":"The end count answers countWordsEqualTo, not countWordsStartingWith. Only \"app\" ends here, but \"apple\" also begins with \"app\", so the prefix count is the pass-through count, which is two.","isCorrect":false},{"id":"walk-below","label":"It walks every node below \"app\" and adds up the end counts, getting 2","rationale":"That reaches the same answer but the long way, visiting the whole subtree. The pass-through count makes the answer one read instead of a subtree walk.","isCorrect":false}],"answer":"It reads the pass-through count on the \"app\" node, which is 2. Both stored words walked through this node and each bumped it, so the prefix count is one number read at the end of the walk, with nothing below to explore."},{"id":"erase-app","title":"Erasing \"app\" once, what happens to the counts along its path?","summary":"\"app\" is erased once. \"apple\" is left untouched and still begins with \"app\".","prompt":"erase walks a, p, p, the same path \"app\" was inserted along.","options":[{"id":"dec-path","label":"Subtract one from the pass-through count on each of a, p, p, and one from the end count on the last p","rationale":"Erasing one occurrence undoes one insert: it walks the path and drops each node's pass-through count by one, so \"app\" reads one again, and drops the end count on the final p so countWordsEqualTo(\"app\") becomes zero. \"apple\" still passes through, so the counts settle at one, not zero.","isCorrect":true},{"id":"remove-nodes","label":"Delete the a, p, p nodes so \"app\" is gone","rationale":"Deleting the nodes would take \"apple\" with them, since it runs through the same a, p, p. Erase only adjusts counts; the shared path stays as long as another word needs it.","isCorrect":false},{"id":"end-only","label":"Only drop the end count on the last p and leave the pass-through counts","rationale":"Leaving the pass-through counts would make countWordsStartingWith(\"app\") still read two, even though only \"apple\" remains. Erase must lower the pass-through count on every node along the path as well.","isCorrect":false}],"answer":"Subtract one from the pass-through count on each node a, p, p and one from the end count on the last p. \"app\" reads one again because \"apple\" still passes through, and countWordsEqualTo(\"app\") falls to zero. The shared path survives for the word that still needs it."}]},{"id":"erase-pitfall","kind":"pitfall","chapter":"Trace it","eyebrow":"Spot the trap","title":"Can erase just walk the path and decrement?","workspacePanel":"trace","summary":"A mirror-image erase walks the word and subtracts one from each pass-through count. For words that are really stored, every count lands right. Watch what it does to a word that was never inserted.","pitfall":"The erase below decrements the pass-through count on every node of the word's path without first checking that the word is actually stored.","whyItMatters":"With only \"apple\" stored, erase(\"app\") walks a, p, p and subtracts one from each, even though \"app\" was never inserted. The \"app\" node falls from one to zero, so countWordsStartingWith(\"app\") now reads zero and loses \"apple\", which still begins with \"app\". A missing word must leave every count untouched, so erase has to confirm the word exists before it changes anything.","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        self.word_count: int = 0\n        self.prefix_count: int = 0\n\nclass TrieCounter:\n    def __init__(self) -> None:\n        self.root: TrieNode = TrieNode()\n\n    def erase(self, word: str) -> None:\n        node: TrieNode = self.root\n        for char in word:\n            next_node: TrieNode = node.children[char]\n            next_node.prefix_count -= 1\n            node = next_node\n        node.word_count -= 1","steps":[{"id":"e-a","title":"erase(\"app\") drops the count at a","codeLine":16,"summary":"Only \"apple\" is stored, so the pass-through count on a, p, p, l, e each reads 1. The walk steps onto a and subtracts one, dropping its count to 0 before anyone checked whether \"app\" was ever inserted.","state":{"graph":{"nodes":[{"id":"a","label":"a · 0"},{"id":"ap","label":"p · 1"},{"id":"app","label":"p · 1"},{"id":"appl","label":"l · 1"},{"id":"apple","label":"e · 1"}],"edges":[["a","ap"],["ap","app"],["app","appl"],["appl","apple"]],"current":"a"}}},{"id":"e-p","title":"And drops the count at the first p","codeLine":16,"summary":"The walk steps onto the first p and subtracts again, dropping its count from 1 to 0 too. \"apple\" still runs through this node, but the count no longer says so.","state":{"graph":{"nodes":[{"id":"a","label":"a · 0"},{"id":"ap","label":"p · 0"},{"id":"app","label":"p · 1"},{"id":"appl","label":"l · 1"},{"id":"apple","label":"e · 1"}],"edges":[["a","ap"],["ap","app"],["app","appl"],["appl","apple"]],"current":"ap","visited":["a"],"activeEdges":[["a","ap"]]}}},{"id":"e-pp","title":"The \"app\" count hits zero","codeLine":16,"summary":"The last p of \"app\" drops from 1 to 0 as well. \"apple\" still passes through this node, yet its pass-through count now reads 0.","state":{"graph":{"nodes":[{"id":"a","label":"a · 0"},{"id":"ap","label":"p · 0"},{"id":"app","label":"p · 0"},{"id":"appl","label":"l · 1"},{"id":"apple","label":"e · 1"}],"edges":[["a","ap"],["ap","app"],["app","appl"],["appl","apple"]],"current":"app","visited":["a","ap"],"activeEdges":[["ap","app"]]}}},{"id":"bad-read","title":"The walk is done, and \"apple\" is lost","codeLine":18,"summary":"The erase walk has finished. A later countWordsStartingWith(\"app\") would walk a, p, p, land on the \"app\" node, and read its count: 0. The right answer is 1, because \"apple\" is still stored and still begins with \"app\". Erasing a word that was never there corrupted a word that was.","state":{"graph":{"nodes":[{"id":"a","label":"a · 0"},{"id":"ap","label":"p · 0"},{"id":"app","label":"p · 0 (want 1)"},{"id":"appl","label":"l · 1"},{"id":"apple","label":"e · 1"}],"edges":[["a","ap"],["ap","app"],["app","appl"],["appl","apple"]],"current":"app","visited":["a","ap","appl","apple"]}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"class TrieNode {\n    constructor() {\n        this.children = new Map();\n        this.isEnd = false;\n        this.wordCount = 0;\n        this.prefixCount = 0;\n    }\n}\n\nclass TrieCounter {\n    constructor() {\n        this.root = new TrieNode();\n    }\n\n    erase(word) {\n        let node = this.root;\n        for (const char of word) {\n            const nextNode = node.children.get(char);\n            nextNode.prefixCount--;\n            node = nextNode;\n        }\n        node.wordCount--;\n    }\n}","lineMap":{"3":3,"4":4,"5":5,"6":6,"10":12,"13":16,"14":17,"15":18,"16":19,"17":20,"18":22},"statementBundles":{"6":{"startLine":6,"endLine":11},"10":{"startLine":12,"endLine":15},"17":{"startLine":20,"endLine":21},"18":{"startLine":22,"endLine":24}},"alternateStyles":{"close-to-source":{"code":"class TrieNode {\n    constructor() {\n        this.children = new Map();\n        this.isEnd = false;\n        this.wordCount = 0;\n        this.prefixCount = 0;\n    }\n}\n\nclass TrieCounter {\n    constructor() {\n        this.root = new TrieNode();\n    }\n\n    erase(word) {\n        let node = this.root;\n        for (const char of word) {\n            const nextNodeValue = node.children.get(char);\n            if (nextNodeValue === undefined) throw new Error(\"KeyError\");\n            const nextNode = nextNodeValue;\n            nextNode.prefixCount--;\n            node = nextNode;\n        }\n        node.wordCount--;\n    }\n}","lineMap":{"3":3,"4":4,"5":5,"6":6,"10":12,"13":16,"14":17,"15":18,"16":21,"17":22,"18":24},"statementBundles":{"6":{"startLine":6,"endLine":11},"10":{"startLine":12,"endLine":15},"15":{"startLine":18,"endLine":20},"17":{"startLine":22,"endLine":23},"18":{"startLine":24,"endLine":26}}}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"class TrieNode {\n    children: Map<string, TrieNode>;\n    isEnd: boolean;\n    prefixCount: number;\n    wordCount: number;\n\n    constructor() {\n        this.children = new Map();\n        this.isEnd = false;\n        this.wordCount = 0;\n        this.prefixCount = 0;\n    }\n}\n\nclass TrieCounter {\n    root: TrieNode;\n\n    constructor() {\n        this.root = new TrieNode();\n    }\n\n    erase(word: string): void {\n        let node = this.root;\n        for (const char of word) {\n            const nextNode = node.children.get(char)!;\n            nextNode.prefixCount--;\n            node = nextNode;\n        }\n        node.wordCount--;\n    }\n}","lineMap":{"3":8,"4":9,"5":10,"6":11,"10":19,"13":23,"14":24,"15":25,"16":26,"17":27,"18":29},"statementBundles":{"6":{"startLine":11,"endLine":18},"10":{"startLine":19,"endLine":22},"17":{"startLine":27,"endLine":28},"18":{"startLine":29,"endLine":31}},"alternateStyles":{"close-to-source":{"code":"class TrieNode {\n    children: Map<string, TrieNode>;\n    isEnd: boolean;\n    prefixCount: number;\n    wordCount: number;\n\n    constructor() {\n        this.children = new Map();\n        this.isEnd = false;\n        this.wordCount = 0;\n        this.prefixCount = 0;\n    }\n}\n\nclass TrieCounter {\n    root: TrieNode;\n\n    constructor() {\n        this.root = new TrieNode();\n    }\n\n    erase(word: string): void {\n        let node = this.root;\n        for (const char of word) {\n            const nextNodeValue = node.children.get(char);\n            if (nextNodeValue === undefined) throw new Error(\"KeyError\");\n            const nextNode = nextNodeValue;\n            nextNode.prefixCount--;\n            node = nextNode;\n        }\n        node.wordCount--;\n    }\n}","lineMap":{"3":8,"4":9,"5":10,"6":11,"10":19,"13":23,"14":24,"15":25,"16":28,"17":29,"18":31},"statementBundles":{"6":{"startLine":11,"endLine":18},"10":{"startLine":19,"endLine":22},"15":{"startLine":25,"endLine":27},"17":{"startLine":29,"endLine":30},"18":{"startLine":31,"endLine":33}}}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"class TrieNode {\n    Map<String, TrieNode> children;\n    boolean isEnd;\n    int prefixCount;\n    int wordCount;\n\n    public TrieNode() {\n        this.children = new HashMap<String, TrieNode>();\n        this.isEnd = false;\n        this.wordCount = 0;\n        this.prefixCount = 0;\n    }\n}\nclass TrieCounter {\n    TrieNode root;\n\n    public TrieCounter() {\n        this.root = new TrieNode();\n    }\n\n    public void erase(String word) {\n        TrieNode node = this.root;\n        for (char char_ : word.toCharArray()) {\n            TrieNode nextNode = node.children.get(String.valueOf(char_));\n            nextNode.prefixCount--;\n            node = nextNode;\n        }\n        node.wordCount--;\n    }\n}","lineMap":{"3":8,"4":9,"5":10,"6":11,"10":18,"13":22,"14":23,"15":24,"16":25,"17":26,"18":28},"statementBundles":{"6":{"startLine":11,"endLine":17},"10":{"startLine":18,"endLine":21},"17":{"startLine":26,"endLine":27},"18":{"startLine":28,"endLine":30}},"alternateStyles":{"close-to-source":{"code":"class TrieNode {\n\n\n    Map<String, TrieNode> children;\n    boolean isEnd;\n    int prefixCount;\n    int wordCount;\n\n    public TrieNode() {\n        this.children = new HashMap<String, TrieNode>();\n        this.isEnd = false;\n        this.wordCount = 0;\n        this.prefixCount = 0;\n    }\n}\nclass TrieCounter {\n    static <K, V> V requireMapValue(Map<K, V> values, K key) { if (!values.containsKey(key)) throw new NoSuchElementException(\"KeyError\"); return values.get(key); }\n\n    TrieNode root;\n\n    public TrieCounter() {\n        this.root = new TrieNode();\n    }\n\n    public void erase(String word) {\n        TrieNode node = this.root;\n        for (char char_ : word.toCharArray()) {\n            TrieNode nextNode = requireMapValue(node.children, String.valueOf(char_));\n            nextNode.prefixCount--;\n            node = nextNode;\n        }\n        node.wordCount--;\n    }\n}","lineMap":{"3":10,"4":11,"5":12,"6":13,"10":22,"13":26,"14":27,"15":28,"16":29,"17":30,"18":32},"statementBundles":{"6":{"startLine":13,"endLine":21},"10":{"startLine":22,"endLine":25},"17":{"startLine":30,"endLine":31},"18":{"startLine":32,"endLine":34}}}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"public class TrieNode\n{\n    public Dictionary<string, TrieNode> children;\n    public bool isEnd;\n    public int prefixCount;\n    public int wordCount;\n\n    public TrieNode()\n    {\n        this.children = new Dictionary<string, TrieNode>();\n        this.isEnd = false;\n        this.wordCount = 0;\n        this.prefixCount = 0;\n    }\n}\n\npublic class TrieCounter\n{\n    public TrieNode root;\n\n    public TrieCounter()\n    {\n        this.root = new TrieNode();\n    }\n\n    public void Erase(string word)\n    {\n        TrieNode node = this.root;\n        foreach (char char_ in word) {\n            TrieNode nextNode = node.children[char_.ToString()];\n            nextNode.prefixCount -= 1;\n            node = nextNode;\n        }\n        node.wordCount -= 1;\n    }\n}","lineMap":{"3":10,"4":11,"5":12,"6":13,"10":23,"13":28,"14":29,"15":30,"16":31,"17":32,"18":34},"statementBundles":{"6":{"startLine":13,"endLine":22},"10":{"startLine":23,"endLine":27},"17":{"startLine":32,"endLine":33},"18":{"startLine":34,"endLine":36}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"struct TrieNode;\nstruct TrieCounter;\n\nstruct TrieNode {\n    unordered_map<string, TrieNode*> children;\n    bool is_end;\n    int prefix_count;\n    int word_count;\n\n    TrieNode() {\n        this->children = unordered_map<string, TrieNode*>{};\n        this->is_end = false;\n        this->word_count = 0;\n        this->prefix_count = 0;\n    }\n};\n\nstruct TrieCounter {\n    TrieNode* root;\n\n    TrieCounter() {\n        this->root = new TrieNode();\n    }\n\n    void erase(string word) {\n        TrieNode* node = this->root;\n        for (char ch : word) {\n            TrieNode* next_node = node->children.at(string(1, ch));\n            next_node->prefix_count -= 1;\n            node = next_node;\n        }\n        node->word_count -= 1;\n    }\n};","lineMap":{"3":11,"4":12,"5":13,"6":14,"10":22,"13":26,"14":27,"15":28,"16":29,"17":30,"18":32},"statementBundles":{"6":{"startLine":14,"endLine":21},"10":{"startLine":22,"endLine":25},"17":{"startLine":30,"endLine":31},"18":{"startLine":32,"endLine":34}}}}}},{"id":"ready-to-code","kind":"info","chapter":"Code","eyebrow":"Get ready to code","title":"Turn the counts into code","workspacePanel":"visualizer","summary":"The whole flow hinges on one rule: change a count only after you know the word is really there.","body":["Words that begin alike share their opening nodes, so each node carries two separate numbers: how many words pass through it, and how many end exactly there. Keeping those counts apart is what lets \"app\" read 1 as an exact word and 2 as a prefix once \"apple\" joins it.","Every operation is a walk down that shared path. The one place to be careful is erase: because it lowers the same counts insert raised, it has to confirm the word is really stored before it touches anything, or decrementing a missing word's path drops shared counts and loses a word that passes through the same nodes."],"ctaLabel":"Start coding","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready","state":{"graph":{"nodes":[{"id":"a","label":"a · 2"},{"id":"ap","label":"p · 2"},{"id":"app","label":"p · 2 (end 1)"},{"id":"appl","label":"l · 1"},{"id":"apple","label":"e · 1 (end 1)"}],"edges":[["a","ap"],["ap","app"],["app","appl"],["appl","apple"]],"visited":["app","apple"]}}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build TrieCounter with prefix counts","eyebrow":"Build the solution","summary":"Create two counter roles, update both during insertion, return each matching count, then guard erase and reverse both updates.","workspacePanel":"code","checkpoints":[{"id":"node-class","title":"Create counting trie nodes","description":"Give each node child storage plus separate zeroed counters for words passing through and words ending there.","commonMistakes":["Only storing raw words","Mixing prefix and exact counts into one value"],"hint":"Separate child links from terminal and prefix metadata.","semanticSpec":{"intent":"Initialize the two distinct counting roles on every trie node.","doneWhen":"A node initializes child-link storage and at least two independent numeric counters.","shouldFailWhen":"This step should fail if the node has only one counter or no counting state.","roles":["trie node","children","prefix count","exact-word count"],"mustProve":["Two independent numeric counter fields are initialized with the trie node state."],"mustNotAccept":["A node with only one number for both exact and prefix answers."],"equivalentVariants":["Choose any field names for the two numeric roles."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"initializes_trie_counter_node_state","scope":"counter-node-class","readMode":"tree-trie-value-query-v1"}]}},{"id":"trie-root","title":"Initialize root","description":"Create the persistent root node for all operations.","commonMistakes":["Creating a new root per operation","Leaving the root unset"],"hint":"The constructor should store one root trie node.","semanticSpec":{"intent":"Initialize persistent trie root state.","doneWhen":"The class constructor stores a root trie node.","shouldFailWhen":"This step should fail if operations cannot share a root.","roles":["trie root"],"mustProve":["A persistent trie root is initialized."],"mustNotAccept":["A local root inside only one method."],"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-word","title":"Insert words","description":"Walk the word one character at a time and create any missing child nodes.","commonMistakes":["Storing the whole word without creating a path","Forgetting to create missing child nodes"],"hint":"Every character should advance to a child node, creating it if needed.","semanticSpec":{"intent":"Insert a word into the trie.","operations":["insert"],"doneWhen":"The path walk creates missing trie nodes and reaches the terminal node.","shouldFailWhen":"This step should fail if inserted words are not represented as trie paths.","roles":["trie path","terminal node"],"mustProve":["Words are inserted as trie paths."],"mustNotAccept":["Appending words to a flat list only."],"equivalentVariants":["Use `setdefault`, explicit membership checks, or equivalent child creation."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"creates_trie_child_path_on_insert","scope":"insert-method","readMode":"tree-trie-value-query-v1"}]}},{"id":"insert-prefix-count","title":"Count every node the word passes through","description":"After each character advances to its child, increment that node's pass-through counter once.","commonMistakes":["Incrementing only the final node","Incrementing before advancing and counting the root instead"],"hint":"Each visited child represents one more stored word sharing that prefix.","semanticSpec":{"intent":"Maintain the prefix-count role during insertion.","operations":["insert"],"doneWhen":"Insertion increments one numeric node field at every step of the trie path.","shouldFailWhen":"This step should fail if insertion updates the counter only at the terminal node.","roles":["insert path","prefix count"],"mustProve":["Insertion increments the same counter along the entire path."],"mustNotAccept":["A terminal-only increment."],"equivalentVariants":["Advance through a helper or directly inside the loop."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"increments_trie_prefix_count_on_insert","scope":"insert-prefix-count","readMode":"tree-trie-value-query-v1"}]}},{"id":"insert-exact-count","title":"Count words that end at the terminal node","description":"After the full path is consumed, increment a different counter on the final node once.","commonMistakes":["Reusing the pass-through counter","Setting a boolean that loses duplicate occurrences"],"hint":"Only the final node receives this update, because only one word ending is being added.","semanticSpec":{"intent":"Maintain the exact-word-count role during insertion.","operations":["insert"],"doneWhen":"Insertion increments a second numeric field only after the path walk finishes.","shouldFailWhen":"This step should fail if no terminal counter is incremented or both roles use one field.","roles":["terminal node","exact-word count"],"mustProve":["Insertion increments a distinct terminal counter."],"mustNotAccept":["A boolean terminal marker as the only exact-word state."],"equivalentVariants":["Keep or omit a separate boolean marker in addition to the count."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"increments_trie_exact_count_on_insert","scope":"insert-exact-count","readMode":"tree-trie-value-query-v1"}]}},{"id":"exact-search","title":"Return the exact-word count","description":"Walk the full word, return zero when its path is missing, and otherwise return the counter for words ending at the final node.","commonMistakes":["Returning the pass-through counter","Returning a boolean instead of the number of copies"],"hint":"The final node already separates words that end here from words that merely continue through it.","semanticSpec":{"intent":"Return the exact multiplicity stored at the terminal node.","operations":["countWordsEqualTo"],"doneWhen":"The query returns zero for a missing path and otherwise returns the same terminal counter incremented by insertion.","shouldFailWhen":"This step should fail if the method returns the prefix counter, a boolean, or a constant.","roles":["query word","terminal node","exact-word count"],"mustProve":["Exact queries return the terminal counter maintained by insertion."],"mustNotAccept":["Returning the pass-through counter from the final node."],"equivalentVariants":["Share a traversal helper or walk the path directly."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"returns_trie_exact_count","scope":"exact-count-method","readMode":"tree-trie-value-query-v1"}]}},{"id":"prefix-search","title":"Return the prefix count","description":"Walk the prefix path, return zero when it is missing, and otherwise return the counter incremented at every node during insertion.","commonMistakes":["Returning the exact-word counter","Exploring the subtree instead of reading the stored count"],"hint":"The pass-through counter at the final prefix node already summarizes every stored continuation.","semanticSpec":{"intent":"Return how many stored words pass through the final prefix node.","operations":["countWordsStartingWith"],"doneWhen":"The query returns zero for a missing path and otherwise returns the same per-node counter incremented by insertion.","shouldFailWhen":"This step should fail if the method returns the exact-word counter, a boolean, or a constant.","roles":["prefix","current trie node","prefix count"],"mustProve":["Prefix queries return the path counter maintained by insertion."],"mustNotAccept":["Returning the number of words ending exactly at the prefix node."],"equivalentVariants":["Share a traversal helper or walk the path directly."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"returns_trie_prefix_count","scope":"prefix-count-method","readMode":"tree-trie-value-query-v1"}]}},{"id":"exact-exists","title":"Expose exact-word existence","description":"Walk the full word and report whether at least one copy ends at the final node.","commonMistakes":["Treating a prefix path as an exact word","Ignoring that erase can reduce the exact count to zero"],"hint":"Exact existence follows from whether the terminal word state still represents a stored copy.","semanticSpec":{"intent":"Support the public exact-word existence query.","operations":["search"],"doneWhen":"The method follows trie links and returns terminal word state at the end.","shouldFailWhen":"This step should fail if a prefix is accepted as an exact word.","roles":["query word","terminal node"],"mustProve":["Exact existence uses trie traversal and terminal state."],"mustNotAccept":["Prefix-only lookup."],"equivalentVariants":["Return a terminal marker or derive existence from the exact count."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"searches_exact_trie_word","scope":"search-method","readMode":"tree-trie-value-query-v1"}]}},{"id":"prefix-exists","title":"Expose prefix existence","description":"Walk the prefix and report whether any stored word still passes through its final node.","commonMistakes":["Requiring the prefix itself to be a complete word","Returning true for a path whose count fell to zero"],"hint":"Prefix existence follows from whether the final prefix node still represents at least one stored continuation.","semanticSpec":{"intent":"Support the public prefix-existence query.","operations":["startsWith"],"doneWhen":"The method follows trie child links and succeeds only while the prefix remains represented.","shouldFailWhen":"This step should fail if prefix lookup does not traverse trie links.","roles":["prefix","current trie node"],"mustProve":["Prefix existence uses trie traversal."],"mustNotAccept":["A full scan of every stored word."],"equivalentVariants":["Return a positive prefix-count check or an equivalent path-existence result."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"checks_trie_prefix","scope":"startswith-method","readMode":"tree-trie-value-query-v1"}]}},{"id":"erase-guard","title":"Leave missing words untouched","description":"Before decrementing anything, stop when the exact-word query reports that no copy remains.","commonMistakes":["Checking only whether the prefix path exists","Decrementing first and checking afterward"],"hint":"A word can have a path in the trie while its exact count is zero.","semanticSpec":{"intent":"Guard erase with the exact multiplicity query.","operations":["erase"],"doneWhen":"Erase exits on a zero result from the exact-count workflow before performing counter mutations.","shouldFailWhen":"This step should fail if erasing a missing word can reach the decrement logic.","roles":["erase","exact-word count","early exit"],"mustProve":["The zero exact-count result guards the erase mutations."],"mustNotAccept":["A prefix-existence check that allows deleting an absent exact word."],"equivalentVariants":["Call the exact query directly or a shared helper returning the same count."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"guards_missing_trie_erase","scope":"erase-guard","readMode":"tree-trie-value-query-v1"}]}},{"id":"erase-prefix-count","title":"Remove one pass from every node","description":"Walk the word's path and decrement the same pass-through counter that insertion incremented at each child.","commonMistakes":["Decrementing only the terminal node","Updating a different field from insertion"],"hint":"Erasing one copy reverses exactly one prefix contribution at every character.","semanticSpec":{"intent":"Reverse the per-node prefix-count updates.","operations":["erase"],"doneWhen":"Erase decrements the insertion path counter once at every node on the word path.","shouldFailWhen":"This step should fail if any prefix contribution remains after a valid erase.","roles":["erase path","prefix count"],"mustProve":["Erase decrements the same path counter used by insertion and prefix queries."],"mustNotAccept":["Changing an unrelated numeric field along the path."],"equivalentVariants":["Use a saved path or traverse the children again."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"decrements_trie_prefix_count_on_erase","scope":"erase-prefix-count","readMode":"tree-trie-value-query-v1"}]}},{"id":"erase-exact-count","title":"Remove one exact ending","description":"After reaching the final node, decrement the same terminal counter returned by the exact-word query.","commonMistakes":["Clearing every duplicate at once","Decrementing the pass-through counter twice"],"hint":"One erase reverses one terminal increment, even when other copies remain.","semanticSpec":{"intent":"Reverse the terminal exact-count update.","operations":["erase"],"doneWhen":"Erase decrements the terminal counter maintained by insertion and returned by exact queries.","shouldFailWhen":"This step should fail if the exact multiplicity does not fall by one.","roles":["terminal node","exact-word count"],"mustProve":["Erase decrements the same terminal counter used by insertion and exact queries."],"mustNotAccept":["Resetting a boolean without decrementing the duplicate count."],"equivalentVariants":["Update a terminal counter with any learner-chosen field name."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"decrements_trie_exact_count_on_erase","scope":"erase-exact-count","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 count on every node turns a prefix question into one read instead of a subtree walk.","body":["Words that begin alike share their opening nodes, so the dictionary becomes a tree where each word is a path of characters. Two numbers on each node carry the answers: how many words pass through it, and how many end exactly there.","Insert raises both kinds of count along the path; erase lowers the same counts, but only after confirming the word is really stored. That ordering is what keeps a missing erase from corrupting a word that shares its prefix."],"takeaways":[{"title":"Prefix counts ride on every node","body":"Bumping a pass-through count on each node an insert steps onto means countWordsStartingWith reads one number at the end of its walk, O(L) in the query length, instead of summing end marks across the whole subtree below the prefix."},{"title":"Two counts answer two questions","body":"The end count on the final node answers countWordsEqualTo, while the pass-through count answers countWordsStartingWith, which is why \"app\" can read 1 as an exact word and 2 as a prefix once \"apple\" is also stored."},{"title":"Erase checks before it changes anything","body":"Because erase lowers the same counts insert raised, it must confirm the word exists first; decrementing the path of a word that was never inserted drops shared counts to zero and loses other words that pass through the same nodes."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"},"starterFunctionName":"TrieCounter","tags":["Trie","Prefix Tree","Design"]}
