{"id":"map-sum-pairs","title":"Map Sum Pairs","difficulty":"medium","patterns":["trie"],"primaryConcept":"trie-basics","concepts":["trie-basics"],"problemForm":"application","companies":["Amazon","Google","Meta","Microsoft"],"category":"trees-graphs","executionStyle":"ops-class","compareMode":"exact","syntheticTestConfig":{"inputShape":"operations","primaryParam":"operations","secondaryParam":"arguments","sizeMetric":"op-count","opVocabulary":[{"name":"MapSum","arity":0,"weight":1},{"name":"insert","arity":2,"argTypes":["string","integer"],"weight":4},{"name":"sum","arity":1,"argTypes":["string"],"weight":3}]},"description":"Design a `MapSum` class that stores string keys with integer values and can return the sum of all values whose keys start with a given prefix.\n\nImplement:\n- `insert(key, val)`: set `key` to `val`, replacing any previous value for that exact key\n- `sum(prefix)`: return the total value of every stored key that starts with `prefix`","examples":[{"input":"operations = [\"MapSum\",\"insert\",\"sum\",\"insert\",\"sum\"]\narguments = [[],[\"apple\",3],[\"ap\"],[\"app\",2],[\"ap\"]]","output":"[null,null,3,null,5]","explanation":"After inserting apple=3, prefix ap sums to 3. After adding app=2, prefix ap sums to 5."},{"input":"operations = [\"MapSum\",\"insert\",\"insert\",\"sum\"]\narguments = [[],[\"apple\",3],[\"apple\",2],[\"ap\"]]","output":"[null,null,null,2]","explanation":"The second insert replaces apple's value, so the prefix sum uses 2 instead of 3."}],"constraints":[{"id":"1-len-key-len-prefix-50","text":"1 <= len(key), len(prefix) <= 50"},{"id":"key-and-prefix-consist-only-of-lowercase-english-letters","text":"key and prefix consist only of lowercase English letters"},{"id":"1-val-1000","text":"1 <= val <= 1000"},{"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.value = 0\n\nclass MapSum:\n    def __init__(self):\n        # Your code here\n        pass\n\n    def insert(self, key: str, val: int) -> None:\n        # Your code here\n        pass\n\n    def startsWith(self, prefix: str) -> bool:\n        # Optional helper for prefix traversal\n        pass\n\n    def sum(self, prefix: str) -> int:\n        # Your code here\n        pass","functionName":"MapSum","testCases":[{"id":"1","input":{"operations":["MapSum","insert","sum","insert","sum"],"arguments":[[],["apple",3],["ap"],["app",2],["ap"]]},"expected":[null,null,3,null,5],"description":"Canonical prefix sum example."},{"id":"2","input":{"operations":["MapSum","insert","insert","sum"],"arguments":[[],["apple",3],["apple",2],["ap"]]},"expected":[null,null,null,2],"description":"A repeated key replaces its old value."},{"id":"3","input":{"operations":["MapSum","insert","insert","insert","sum","sum"],"arguments":[[],["car",4],["cart",6],["dog",5],["car"],["do"]]},"expected":[null,null,null,null,10,5],"description":"Two different prefix subtrees."},{"id":"4","input":{"operations":["MapSum","insert","sum"],"arguments":[[],["trace",7],["tracer"]]},"expected":[null,null,0],"description":"A longer prefix that is not present returns zero."},{"id":"5","input":{"operations":["MapSum","insert","insert","sum","sum"],"arguments":[[],["a",1],["ab",3],["a"],["ab"]]},"expected":[null,null,null,4,3],"description":"A key can be a prefix of another key."},{"id":"h1","input":{"operations":["MapSum","insert","insert","sum"],"arguments":[[],["apple",3],["app",2],["ap"]]},"description":"Overlapping prefixes accumulate across both keys.","expected":[null,null,null,5]},{"id":"h2","input":{"operations":["MapSum","insert","insert","insert","sum"],"arguments":[[],["a",1],["ab",2],["abc",3],["ab"]]},"description":"A longer prefix only counts matching descendants.","expected":[null,null,null,null,5]},{"id":"h3","input":{"operations":["MapSum","insert","sum","insert","sum"],"arguments":[[],["x",5],["y"],["xy",2],["x"]]},"description":"A missing prefix returns zero before later inserts change the total.","expected":[null,null,0,null,7]},{"id":"h4","input":{"operations":["MapSum","insert","insert","insert","sum"],"arguments":[[],["tree",4],["trie",3],["trip",2],["tri"]]},"description":"Multiple words share the same starting letters.","expected":[null,null,null,null,5]},{"id":"h5","input":{"operations":["MapSum","insert","insert","insert","sum"],"arguments":[[],["m",7],["map",4],["mat",6],["ma"]]},"description":"Prefix totals include every stored descendant.","expected":[null,null,null,null,10]},{"id":"replace-descendant-key","input":{"operations":["MapSum","insert","insert","sum","insert","sum"],"arguments":[[],["apple",3],["app",2],["app"],["apple",5],["app"]]},"description":"Replacing a descendant key updates the prefix total without double-counting.","expected":[null,null,null,5,null,7]},{"id":"replace-root-prefix-key","input":{"operations":["MapSum","insert","insert","sum","insert","sum"],"arguments":[[],["a",10],["aa",5],["a"],["a",1],["a"]]},"description":"A key that is also a prefix can be replaced while keeping child totals.","expected":[null,null,null,15,null,6]}],"hints":[{"level":1,"content":"A trie groups all keys with the same prefix under the same node."},{"level":2,"content":"Store each key's value at its terminal trie node so replacing a key overwrites that terminal value."},{"level":3,"content":"For `sum(prefix)`, walk to the prefix node, then DFS that subtree and add every terminal value."}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"scan-all-keys","name":"Scan all keys","summary":"Store exact keys in a map and scan every key on each sum query.","decisionReason":"Each sum(prefix) checks every stored key character by character, even when most keys diverge at the first letter. A trie walks the prefix once and then only visits keys under that prefix.","complexity":{"time":"O(K * L) per sum","space":"O(K * L)"},"tradeoffs":["Runs in O(K * L) per sum time and uses O(K * L) space."],"isOptimal":false},{"id":"trie-subtree-sum","name":"Trie with subtree DFS","summary":"Store keys in a trie, walk the prefix, then sum values in that prefix subtree.","decisionReason":"The trie path for prefix lands at the subtree containing exactly the matching keys. From there, summing terminal values under that node avoids scanning unrelated keys while still handling replaced exact keys.","complexity":{"time":"O(P + S) per sum","space":"O(T)"},"tradeoffs":["Runs in O(P + S) per sum time and uses O(T) space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"node-class","title":"Create trie nodes","description":"Store child links and a terminal value on each trie node.","commonMistakes":["Using one global value instead of terminal node values","Forgetting child links"],"hint":"Each node needs child links, an end marker, and a stored value.","semanticSpec":{"intent":"Define the node state used by the trie.","doneWhen":"A node constructor initializes child links and terminal state.","shouldFailWhen":"This step should fail if nodes do not own child-link state.","roles":["trie node","children","terminal value"],"mustProve":["Trie node state is initialized in a constructor."],"mustNotAccept":["Representing the trie as a flat map only."],"equivalentVariants":["Use a dictionary/map of child links and any terminal payload state."],"proofSnippets":[{"id":"py-map-sum-node-class","language":"typescript","code":"class TrieNode {\n  children: Record<string, TrieNode>;\n  isEnd: boolean;\n\n  constructor() {\n    const childMap: Record<string, TrieNode> = {};\n    const terminal = false;\n    this.children = childMap;\n    this.isEnd = terminal;\n  }\n}"}]},"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","description":"Create the root trie node when `MapSum` is constructed.","commonMistakes":["Creating a new root inside every operation","Leaving the root uninitialized"],"hint":"The root must persist across insert and sum operations.","semanticSpec":{"intent":"Initialize persistent trie root state for the operation class.","doneWhen":"The constructor stores a root trie node on the instance.","shouldFailWhen":"This step should fail if the root is local to only one method.","roles":["constructor","root node","persistent state"],"mustProve":["A trie root is initialized by the class constructor."],"mustNotAccept":["A root created only inside `insert` or `sum`."],"equivalentVariants":["Use `root`, `head`, or another persistent field for the trie root."],"proofSnippets":[{"id":"py-map-sum-trie-root","language":"typescript","code":"class TrieNode {\n  children: Record<string, TrieNode>;\n  isEnd: boolean;\n\n  constructor() {\n    const childMap: Record<string, TrieNode> = {};\n    const terminal = false;\n    this.children = childMap;\n    this.isEnd = terminal;\n  }\n}\n\nclass MapSum {\n  root: TrieNode;\n\n  constructor() {\n    this.root = new TrieNode();\n  }\n}"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"initializes_trie_root","scope":"trie-class","readMode":"tree-trie-value-query-v1"}]}},{"id":"insert-key","title":"Insert keys","description":"Walk or create the path for each inserted key and store its value at the terminal node.","commonMistakes":["Adding only the first character","Accumulating duplicate key values instead of replacing them"],"hint":"Create missing child nodes while walking each key.","semanticSpec":{"intent":"Insert a key by walking its characters through the trie.","doneWhen":"The insert method creates missing child links, advances through each character, and writes terminal state.","shouldFailWhen":"This step should fail if inserted keys are not represented as trie paths.","roles":["key","current node","child link","terminal value"],"mustProve":["The insert method walks the key path and writes terminal state."],"mustNotAccept":["Storing only exact keys in a flat dictionary."],"equivalentVariants":["Use map child links or fixed-size child arrays."],"proofSnippets":[{"id":"py-map-sum-insert-key","language":"typescript","code":"class TrieNode {\n  children: Record<string, TrieNode>;\n  isEnd: boolean;\n\n  constructor() {\n    this.children = {};\n    this.isEnd = false;\n  }\n}\n\nclass MapSum {\n  root: TrieNode;\n\n  constructor() {\n    this.root = new TrieNode();\n  }\n\n  insert(key: string, val: number): void {\n    let node = this.root;\n    for (const ch of key) {\n      if (!node.children[ch]) {\n        node.children[ch] = new TrieNode();\n      }\n      node = node.children[ch];\n    }\n    node.isEnd = true;\n  }\n}"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"inserts_trie_word","scope":"insert-method","readMode":"tree-trie-value-query-v1"}]}},{"id":"prefix-walk","title":"Walk the prefix path","description":"Traverse the trie along the query prefix and stop with zero if the path is missing.","commonMistakes":["Scanning every key for every prefix","Ignoring missing child links"],"hint":"A missing child during prefix traversal means no key can match.","semanticSpec":{"intent":"Use trie child links to decide whether a prefix path exists.","doneWhen":"The code walks prefix characters from the root and returns a miss result when a child link is absent.","shouldFailWhen":"This step should fail if prefix queries do not traverse trie links.","roles":["prefix","current node","child link","missing prefix"],"mustProve":["The code advances through child links for prefix characters."],"mustNotAccept":["Checking prefixes only by string slicing stored keys."],"equivalentVariants":["Use a boolean prefix helper that `sum` calls before descending to the prefix node."],"proofSnippets":[{"id":"py-map-sum-prefix-walk","language":"typescript","code":"class TrieNode {\n  children: Record<string, TrieNode>;\n  isEnd: boolean;\n\n  constructor() {\n    this.children = {};\n    this.isEnd = false;\n  }\n}\n\nclass MapSum {\n  root: TrieNode;\n\n  constructor() {\n    this.root = new TrieNode();\n  }\n\n  insert(key: string, val: number): void {\n    let node = this.root;\n    for (const ch of key) {\n      if (!node.children[ch]) {\n        node.children[ch] = new TrieNode();\n      }\n      node = node.children[ch];\n    }\n    node.isEnd = true;\n  }\n\n  startsWith(prefix: string): boolean {\n    let node = this.root;\n    for (const ch of prefix) {\n      if (!node.children[ch]) {\n        return false;\n      }\n      node = node.children[ch];\n    }\n    return true;\n  }\n}"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"checks_trie_prefix","scope":"startswith-method","readMode":"tree-trie-value-query-v1"}]}},{"id":"sum-subtree","title":"Sum subtree values","description":"DFS from the prefix node and add each terminal value in that subtree.","commonMistakes":["Returning only the prefix node's own value","Skipping descendant keys"],"hint":"Every descendant of the prefix node represents a key with that prefix.","semanticSpec":{"intent":"Accumulate values across the prefix subtree.","doneWhen":"A traversal accumulates each child subtree's total into a running total.","shouldFailWhen":"This step should fail if descendant values are never added.","roles":["subtree node","child node","running total"],"mustProve":["The code additively updates a total while traversing child nodes."],"mustNotAccept":["Returning only a boolean prefix existence result."],"equivalentVariants":["Use recursive DFS or an explicit stack to visit child nodes."],"proofSnippets":[{"id":"py-map-sum-subtree","language":"python","code":"class TrieNode:\n    def __init__(self):\n        self.children = {}\n        self.is_end = False\n        self.value = 0\n\nclass MapSum:\n    def __init__(self):\n        self.root = TrieNode()\n\n    def insert(self, key: str, val: int) -> None:\n        node = self.root\n        for char in key:\n            if char not in node.children:\n                node.children[char] = TrieNode()\n            node = node.children[char]\n        node.is_end = True\n        node.value = val\n\n    def startsWith(self, prefix: str) -> bool:\n        node = self.root\n        for char in prefix:\n            if char not in node.children:\n                return False\n            node = node.children[char]\n        return True\n\n    def sum(self, prefix: str) -> int:\n        if not self.startsWith(prefix):\n            return 0\n        node = self.root\n        for char in prefix:\n            node = node.children[char]\n\n        def dfs(cur: TrieNode) -> int:\n            total = cur.value\n            for child in cur.children.values():\n                total += dfs(child)"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"additively_updates_accumulator","scope":"update-total","readMode":"array-scan-value-query-v1"}]}},{"id":"return-total","title":"Return the prefix total","description":"Return the accumulated total for the prefix subtree.","commonMistakes":["Returning the trie node","Returning the prefix string"],"hint":"The DFS total is the answer for `sum(prefix)`.","semanticSpec":{"intent":"Return the accumulated subtree total as the query answer.","doneWhen":"The `sum` operation returns the numeric total produced from the prefix subtree.","shouldFailWhen":"This step should fail if `sum` returns a node, string, or boolean.","roles":["accumulated total","terminal return"],"mustProve":["The terminal return is the accumulator value."],"mustNotAccept":["Returning the root or prefix node object."],"equivalentVariants":["Return the recursive DFS result or an iteratively accumulated total."],"proofSnippets":[{"id":"py-map-sum-return-total","language":"python","code":"class TrieNode:\n    def __init__(self):\n        self.children = {}\n        self.is_end = False\n        self.value = 0\n\nclass MapSum:\n    def __init__(self):\n        self.root = TrieNode()\n\n    def insert(self, key: str, val: int) -> None:\n        node = self.root\n        for char in key:\n            if char not in node.children:\n                node.children[char] = TrieNode()\n            node = node.children[char]\n        node.is_end = True\n        node.value = val\n\n    def startsWith(self, prefix: str) -> bool:\n        node = self.root\n        for char in prefix:\n            if char not in node.children:\n                return False\n            node = node.children[char]\n        return True\n\n    def sum(self, prefix: str) -> int:\n        if not self.startsWith(prefix):\n            return 0\n        node = self.root\n        for char in prefix:\n            node = node.children[char]\n\n        def dfs(cur: TrieNode) -> int:\n            total = cur.value\n            for child in cur.children.values():\n                total += dfs(child)\n            return total\n\n        return dfs(node)"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_terminal_accumulator","scope":"return-result","readMode":"array-scan-value-query-v1"}]}}],"slides":[{"id":"opener","kind":"info","chapter":"The problem","eyebrow":"Read the problem","title":"Add up the values of every key that starts with a prefix","workspacePanel":"problem","body":["You are building a small store of string keys with integer values. insert(key, val) sets that key to val, replacing any value it held before. sum(prefix) returns the total value of every stored key that begins with prefix.","Many sum calls can share the same prefix, while inserting an existing key replaces its old value. The stored prefix totals must reflect the latest value without scanning every key again."]},{"id":"brute-force","kind":"code-trace","chapter":"The slow way","eyebrow":"The obvious way","title":"Keep keys in a flat map and scan them all","summary":"A plain map of key to value answers every sum correctly, but each query re-scans every stored key to find the matches. Watch how much one call re-reads.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def sum(store: dict[str, int], prefix: str) -> int:\n    total = 0\n    for key, val in store.items():\n        if key.startswith(prefix):\n            total += val\n    return total","steps":[{"id":"scan-apple","title":"Test the first stored key against the prefix","codeLine":4,"summary":"store = {\"apple\": 3, \"app\": 2, \"dog\": 5}, prefix = \"ap\". The scan checks \"apple\", reads a, p to confirm it starts with \"ap\", and adds 3.","state":{"s":"apple","i":1,"total":3,"labels":{"s":"key"}}},{"id":"scan-app","title":"Then test the next key","codeLine":4,"summary":"\"app\" also starts with \"ap\", so the scan reads its characters and adds 2, bringing total to 5.","state":{"s":"app","i":2,"total":5,"labels":{"s":"key"}}},{"id":"scan-dog","title":"And test every remaining key too","codeLine":4,"summary":"\"dog\" shares nothing with \"ap\", but the scan still reads d to rule it out. Every key gets visited, and every later sum walks all of them again.","state":{"s":"dog","i":0,"total":5,"labels":{"s":"key"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"let total = 0;\nfor (const [key, val] of [...store.entries()]) {\n    if (key.startsWith(prefix)) {\n        total += val;\n    }\n}\nreturn total;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":7},"statementBundles":{"5":{"startLine":4,"endLine":6}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"let total = 0;\nfor (const [key, val] of [...store.entries()]) {\n    if (key.startsWith(prefix)) {\n        total += val;\n    }\n}\nreturn total;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":7},"statementBundles":{"5":{"startLine":4,"endLine":6}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int total = 0;\nfor (Map.Entry<String, Integer> item : store.entrySet()) {\n    String key = item.getKey();\n    int val = item.getValue();\n    if (key.startsWith(prefix)) {\n        total += val;\n    }\n}\nreturn total;","lineMap":{"2":1,"3":2,"4":5,"5":6,"6":9},"statementBundles":{"3":{"startLine":2,"endLine":4},"5":{"startLine":6,"endLine":8}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int total = 0;\nforeach (var entry0 in store) {\n    string key = entry0.Key;\n    int val = entry0.Value;\n    if (key.StartsWith(prefix)) {\n        total += val;\n    }\n}\nreturn total;","lineMap":{"2":1,"3":2,"4":5,"5":6,"6":9},"statementBundles":{"3":{"startLine":2,"endLine":4},"5":{"startLine":6,"endLine":8}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int total = 0;\nfor (const auto& [key, val] : store) {\n    if ((key.rfind(prefix, 0) == 0)) {\n        total += val;\n    }\n}\nreturn total;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":7},"statementBundles":{"5":{"startLine":4,"endLine":6}}}}}},{"id":"cost-probe","kind":"case-probe","chapter":"The slow way","eyebrow":"Count the work","title":"How much does one sum call read?","workspacePanel":"visualizer","summary":"The store holds k keys, each up to length L, and the matching keys can be anywhere in it.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"work-count-state","state":{"seen":{"apple":"scanned","app":"scanned","dog":"scanned"},"labels":{"seen":"keys read this call"},"keys (k)":3,"longest key (L)":5,"characters read":"up to k x L"}}]},"options":[{"id":"all-keys","label":"Up to every character of every key, about k times L per call","rationale":"A flat map has no idea which keys share the prefix, so each sum re-reads all k keys character by character, up to L each, to decide which ones match. The keys never changed between calls, yet every query pays the full k times L again.","isCorrect":true},{"id":"prefix-only","label":"Just the characters of the prefix, once","rationale":"That is the cost we want, but a flat map cannot reach it. With nothing grouping keys by their shared opening, the only way to find which keys start with the prefix is to test each stored key in turn.","isCorrect":false},{"id":"match-count","label":"Only the keys that actually match the prefix","rationale":"The scan still has to look at the non-matching keys to reject them. \"dog\" never contributes to sum(\"ap\"), yet the loop reads it every time to learn that, so the cost grows with all k keys.","isCorrect":false}],"answer":"About k times L per call. With keys sitting in a flat map, every sum re-reads all of them character by character, because nothing records that \"apple\" and \"app\" already share the same opening \"ap\"."},{"id":"idea-bridge","kind":"info","chapter":"The idea","eyebrow":"Find the structure","title":"The flat map pays for keys it has already seen","workspacePanel":"visualizer","body":["Every sum re-reads all k keys, up to L characters each, even though the keys have not changed since the last call. The cost is k times L per query because nothing in the store records which keys begin alike.","\"apple\" and \"app\" both open with a, p, then \"apple\" keeps going. If the store remembered that shared opening once instead of rediscovering it on every query, a prefix question could go straight to the keys that match."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"shared-opening-state","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"]],"highlighted":["a","ap"]}}}]}},{"id":"approach-selection","kind":"choice","source":"approach-selection","chapter":"The idea","eyebrow":"Pick the approach","title":"Which structure should group shared prefixes?","workspacePanel":"trace"},{"id":"trie-node-state","kind":"case-probe","chapter":"The idea","eyebrow":"Define the nodes","title":"What does the node after walking \"ap\" represent?","summary":"A sum(\"ap\") query has walked from the root through a and p.","workspacePanel":"trace","options":[{"id":"prefix-path","label":"The prefix shared by every key below that node","rationale":"Every descendant key has already matched ap, so the subtree is exactly the region sum(\"ap\") needs to total.","isCorrect":true},{"id":"one-key","label":"Only the first full key inserted with that prefix","rationale":"The node can have many descendants, including apple and app. It is a prefix position, not one key."},{"id":"total-cache","label":"The final sum value for every possible query","rationale":"This design gathers the subtree on demand. The node first represents the walked prefix."}],"answer":"The node reached by \"ap\" represents that prefix, and its subtree contains keys that start with it."},{"id":"structure-probe","kind":"case-probe","chapter":"The idea","eyebrow":"Find the structure","title":"What do keys that share a prefix let you group together?","workspacePanel":"visualizer","summary":"\"apple\" and \"app\" begin the same way, sharing a, p, p before \"apple\" continues.","options":[{"id":"shared-subtree","label":"Their shared opening as one path, so every key under a prefix sits in that prefix's subtree","rationale":"Make each key a walk of characters from a common start, and keys that begin alike reuse the same early steps. The prefix \"ap\" becomes a single node, and every key starting with \"ap\" hangs somewhere below it. A prefix question turns into \"what lives under this node\", which is exactly the set sum needs.","isCorrect":true},{"id":"sorted","label":"Their alphabetical order, so a binary search can jump to the prefix","rationale":"Sorting keys puts a prefix's matches in one contiguous run, but you still scan that whole run to add them, and re-sort on every insert. Ordering finds where the matches start; it does not collapse the shared opening into one place you can total at once.","isCorrect":false},{"id":"buckets","label":"Their first letter, bucketed so all keys starting with the same letter sit together","rationale":"A single-letter bucket helps only one-character prefixes. sum(\"ap\") would still scan every key in the \"a\" bucket to find which ones continue with p, so the work stays proportional to all keys sharing just the first letter.","isCorrect":false}],"answer":"Their shared opening becomes one path from a common start, so every key beginning with a prefix lands in that prefix's subtree. Walk to the \"ap\" node and everything below it is exactly the keys sum(\"ap\") must add. \"apple\" and \"app\" share a, p, p and only split when \"apple\" continues.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"shared-state","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":"ap","highlighted":["app"]}}}]}},{"id":"value-probe","kind":"case-probe","chapter":"The idea","eyebrow":"Find the structure","title":"If sum gathers the subtree on demand, where does each key's value belong?","workspacePanel":"visualizer","summary":"\"apple\" is worth 3 and \"app\" is worth 2; both run through the shared \"ap\" path.","options":[{"id":"terminal-value","label":"On the character where each full key ends","rationale":"Store a key's value on the node its last character lands on. Then sum(\"ap\") walks to the \"ap\" node and adds every value sitting in the subtree below it, which is exactly the keys that begin with \"ap\". The value of \"app\" sits on its terminal node, the value of \"apple\" on its own, and the subtree total combines them.","isCorrect":true},{"id":"running-on-prefix","label":"Add each key's value into every node along its path, so a prefix node already holds the running total","rationale":"That is a different, valid design: cached prefix totals make sum a single read instead of a subtree walk. But it answers a question we are not asking here, where sum gathers the subtree on demand. With cached totals the work and care move to insert, which must adjust every node on the path and apply the old-value delta when a key is replaced. We will revisit it as a tradeoff later; for the on-demand sum we are building, the value belongs at the terminal node.","isCorrect":false},{"id":"value-on-root","label":"On the root, summed as keys arrive, since the root sees every key","rationale":"A single root total cannot answer a prefix question. sum(\"ap\") needs the keys under \"ap\" alone, not every key ever inserted, so one number at the root throws away the very grouping the tree was built to provide.","isCorrect":false}],"answer":"On the node where each key ends. Because sum walks to the \"ap\" node and adds every value in the subtree below it, the subtree holds exactly the keys starting with \"ap\". The value of \"apple\" and the value of \"app\" each sit on their own terminal node, and the prefix subtree gathers them. Caching running totals on every path node is a fair alternative; it shifts the work to insert.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"value-state","state":{"graph":{"nodes":[{"id":"a","label":"a"},{"id":"ap","label":"p"},{"id":"app","label":"p=2"},{"id":"appl","label":"l"},{"id":"apple","label":"e=3"}],"edges":[["a","ap"],["ap","app"],["app","appl"],["appl","apple"]],"current":"ap","visited":["app","apple"]}}}]}},{"id":"dry-run-setup","kind":"info","chapter":"Trace it","eyebrow":"Watch it move","title":"Insert apple, sum the prefix, insert app, sum again","workspacePanel":"visualizer","body":["Each node keeps a small map from a character to its child, and the node where a key ends stores that key's value. Insert walks the key, following an existing child or creating one, and writes the value onto the node it ends on. sum walks to the prefix node and adds every value in the subtree below it.","\"apple\" is already stored below, worth 3, with its value on the final node. You will run sum(\"ap\"), then insert app=2, then run sum(\"ap\") again, and watch the prefix total change as the second key joins the subtree."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup-state","state":{"graph":{"nodes":[{"id":"a","label":"a"},{"id":"ap","label":"p"},{"id":"app","label":"p"},{"id":"appl","label":"l"},{"id":"apple","label":"e=3"}],"edges":[["a","ap"],["ap","app"],["app","appl"],["appl","apple"]],"visited":["apple"]}}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","chapter":"Trace it","eyebrow":"Trace the walk","title":"Sum a prefix, add a key, sum it again","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"sum-ap-first","state":{"graph":{"nodes":[{"id":"a","label":"a"},{"id":"ap","label":"p"},{"id":"app","label":"p"},{"id":"appl","label":"l"},{"id":"apple","label":"e=3"}],"edges":[["a","ap"],["ap","app"],["app","appl"],["appl","apple"]],"current":"ap","highlighted":["apple"],"visited":["apple"]}}},{"id":"insert-app","state":{"graph":{"nodes":[{"id":"a","label":"a"},{"id":"ap","label":"p"},{"id":"app","label":"p=2"},{"id":"appl","label":"l"},{"id":"apple","label":"e=3"}],"edges":[["a","ap"],["ap","app"],["app","appl"],["appl","apple"]],"current":"app","highlighted":["ap"],"visited":["apple","app"],"activeEdges":[["ap","app"]]}}},{"id":"sum-ap-again","state":{"graph":{"nodes":[{"id":"a","label":"a"},{"id":"ap","label":"p"},{"id":"app","label":"p=2"},{"id":"appl","label":"l"},{"id":"apple","label":"e=3"}],"edges":[["a","ap"],["ap","app"],["app","appl"],["appl","apple"]],"current":"ap","highlighted":["app","apple"],"visited":["apple","app"]}}}]},"beats":[{"id":"sum-ap-first","title":"With only apple stored, what does sum(\"ap\") return?","summary":"Each key's value sits on the node its last letter lands on.","prompt":"Follow a then p to the \"ap\" node and read the values in the subtree below it. What do they add up to?","options":[{"id":"three","label":"3, the one value in the subtree under \"ap\"","rationale":"sum walks to the \"ap\" node and adds every value below it. Only \"apple\" hangs in that subtree, carrying 3, so the total is 3. No other key starts with \"ap\" yet.","isCorrect":true},{"id":"zero","label":"0, because no key is exactly \"ap\"","rationale":"sum asks for keys that begin with the prefix, not keys equal to it. \"ap\" was never inserted, but \"apple\" begins with it and lives in the subtree, so its 3 still counts.","isCorrect":false},{"id":"five","label":"5, since \"app\" will also be under \"ap\"","rationale":"\"app\" has not been inserted yet at this point in the trace. Only \"apple\" sits under \"ap\" so far, so the total is 3 until the next insert adds to the subtree.","isCorrect":false}],"answer":"3. The walk reaches the \"ap\" node and adds every value in its subtree, which holds only \"apple\" worth 3. \"ap\" itself was never a stored key, but it does not need to be; sum counts the keys hanging below it."},{"id":"insert-app","title":"Inserting app=2, where does its value land?","summary":"The path a, p, p already exists from \"apple\", and \"app\" ends on its third character.","prompt":"insert(\"app\", 2) walks a then p then p, all of which already have child nodes from \"apple\".","options":[{"id":"on-app-node","label":"On the existing \"app\" node, which becomes a value-carrying terminal under \"ap\"","rationale":"\"app\" reuses the a, p, p path \"apple\" already built and ends on the third-character node, so insert writes 2 there. That node was only passed through before; now it carries a key's value and joins the subtree under \"ap\".","isCorrect":true},{"id":"new-path","label":"On a fresh path built from the start so \"app\" stays separate from \"apple\"","rationale":"A second path would duplicate the a, p, p that already exists and break the sharing the tree is built on. insert follows existing children whenever the character is present, and all three of \"app\"'s characters already have children.","isCorrect":false},{"id":"on-ap","label":"On the \"ap\" node, since that is the prefix the sum query uses","rationale":"The value belongs on the node where the key ends, which for \"app\" is the third character. Writing it on \"ap\" would claim \"ap\" itself is a stored key and would distort every prefix that passes through it.","isCorrect":false}],"answer":"On the existing \"app\" node. \"app\" walks the same a, p, p that \"apple\" created and ends on the third-character node, so insert writes 2 there. That node now carries a value and sits in the subtree under \"ap\" alongside \"apple\"."},{"id":"sum-ap-again","title":"What does sum(\"ap\") return now?","summary":"The insert wrote 2 on the existing \"app\" node.","prompt":"Walk to the same \"ap\" node and read every value in its subtree. What is the new total?","options":[{"id":"five","label":"5, both stored values together","rationale":"sum gathers every value below the prefix node. The subtree under \"ap\" now holds \"app\" worth 2 and \"apple\" worth 3, so the total is 5. The same walk that returned 3 before now finds one more value waiting in the subtree.","isCorrect":true},{"id":"two","label":"2, the value of the key that ends nearest the \"ap\" node","rationale":"sum is not the closest key; it is the total of every key under the prefix. \"apple\" is still down the same subtree carrying 3, so stopping at \"app\" alone would drop a key that begins with \"ap\".","isCorrect":false},{"id":"three","label":"3, unchanged, because sum already walked this prefix once","rationale":"Nothing is cached between calls; sum re-reads the subtree each time. Since \"app\" joined the subtree after the first query, the second walk sees both values and returns 5.","isCorrect":false}],"answer":"5. The walk lands on the same \"ap\" node and adds every value in its subtree, now \"apple\" worth 3 and \"app\" worth 2. The structural change from the insert is what moved the total from 3 to 5."}]},{"id":"double-count-pitfall","kind":"pitfall","chapter":"Trace it","eyebrow":"Spot the trap","title":"Could insert just add the new value onto the old one?","workspacePanel":"trace","summary":"sum adds values across different keys. If insert also adds values into a terminal node, inserting two fresh keys still totals correctly. Watch what happens when the same key arrives twice.","pitfall":"The insert below reuses the same combining step on the terminal node that sum uses to gather a subtree. Follow the trace and see whether re-inserting a key leaves the right value behind.","whyItMatters":"The trace shows the bug: the insert does node.value += val, so the second insert lands on the same terminal node and computes 3 + 2 = 5 instead of replacing it with 2. sum(\"ap\") then reads 5, but \"apple\" was last set to 2, so the only correct answer is 2. The fix is for insert to write node.value = val, overwriting the terminal value rather than accumulating it, because a key holds one value at a time and a stale addition inflates every prefix that passes through it.","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.value: int = 0\n\ndef insert(root: TrieNode, key: str, val: int) -> None:\n    node = root\n    for ch in key:\n        if ch not in node.children:\n            node.children[ch] = TrieNode()\n        node = node.children[ch]\n    node.is_end = True\n    node.value += val","steps":[{"id":"first-insert","title":"insert(\"apple\", 3) sets the terminal value","codeLine":14,"summary":"The walk builds the path for \"apple\" and lands on its terminal node, which starts at 0 and becomes 0 + 3 = 3. So far this matches what we want.","state":{"graph":{"nodes":[{"id":"a","label":"a"},{"id":"ap","label":"p"},{"id":"app","label":"p"},{"id":"appl","label":"l"},{"id":"apple","label":"e=3"}],"edges":[["a","ap"],["ap","app"],["app","appl"],["appl","apple"]],"current":"apple","visited":["apple"]}}},{"id":"second-insert","title":"insert(\"apple\", 2) adds onto the old value","codeLine":14,"summary":"The same key walks the same path back to the same terminal node, still holding 3. Instead of replacing it, the code does 3 + 2 and leaves 5 on the node that should now read 2.","state":{"graph":{"nodes":[{"id":"a","label":"a"},{"id":"ap","label":"p"},{"id":"app","label":"p"},{"id":"appl","label":"l"},{"id":"apple","label":"e=5"}],"edges":[["a","ap"],["ap","app"],["app","appl"],["appl","apple"]],"current":"apple","highlighted":["apple"]}}},{"id":"wrong-sum","title":"sum(\"ap\") reads the inflated value","codeLine":14,"summary":"sum walks to \"ap\" and adds the subtree, which now holds 5 on the \"apple\" node. It returns 5, but \"apple\" was last set to 2, so the only correct answer is 2.","state":{"graph":{"nodes":[{"id":"a","label":"a"},{"id":"ap","label":"p"},{"id":"app","label":"p"},{"id":"appl","label":"l"},{"id":"apple","label":"e=5"}],"edges":[["a","ap"],["ap","app"],["app","appl"],["appl","apple"]],"current":"ap","highlighted":["apple"],"visited":["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.value = 0;\n    }\n}\n\nlet node = root;\nfor (const ch of key) {\n    if (!node.children.has(ch)) {\n        node.children.set(ch, new TrieNode());\n    }\n    node = node.children.get(ch);\n}\nnode.isEnd = true;\nnode.value += val;","lineMap":{"3":3,"4":4,"5":5,"8":9,"9":10,"10":11,"11":12,"12":14,"13":16,"14":17},"statementBundles":{"5":{"startLine":5,"endLine":7},"11":{"startLine":12,"endLine":13},"12":{"startLine":14,"endLine":15}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"class TrieNode {\n    children: Map<string, TrieNode>;\n    isEnd: boolean;\n    value: number;\n\n    constructor() {\n        this.children = new Map();\n        this.isEnd = false;\n        this.value = 0;\n    }\n}\n\nlet node = root;\nfor (const ch of key) {\n    if (!node.children.has(ch)) {\n        node.children.set(ch, new TrieNode());\n    }\n    node = node.children.get(ch)!;\n}\nnode.isEnd = true;\nnode.value += val;","lineMap":{"3":7,"4":8,"5":9,"8":13,"9":14,"10":15,"11":16,"12":18,"13":20,"14":21},"statementBundles":{"5":{"startLine":9,"endLine":11},"11":{"startLine":16,"endLine":17},"12":{"startLine":18,"endLine":19}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"class TrieNode {\n    Map<String, TrieNode> children;\n    boolean isEnd;\n    int value;\n\n    public TrieNode() {\n        this.children = new HashMap<String, TrieNode>();\n        this.isEnd = false;\n        this.value = 0;\n    }\n}\n\nTrieNode node = root;\nfor (char ch : key.toCharArray()) {\n    if (!node.children.containsKey(String.valueOf(ch))) {\n        node.children.put(String.valueOf(ch), new TrieNode());\n    }\n    node = node.children.get(String.valueOf(ch));\n}\nnode.isEnd = true;\nnode.value += val;","lineMap":{"3":7,"4":8,"5":9,"8":13,"9":14,"10":15,"11":16,"12":18,"13":20,"14":21},"statementBundles":{"5":{"startLine":9,"endLine":11},"11":{"startLine":16,"endLine":17},"12":{"startLine":18,"endLine":19}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"class TrieNode\n{\n    public Dictionary<string, TrieNode> children;\n    public bool isEnd;\n    public int value;\n\n    public TrieNode()\n    {\n        this.children = new Dictionary<string, TrieNode>();\n        this.isEnd = false;\n        this.value = 0;\n    }\n}\n\nTrieNode node = root;\nforeach (char ch in key) {\n    if (!node.children.ContainsKey(ch.ToString())) {\n        node.children[ch.ToString()] = new TrieNode();\n    }\n    node = node.children[ch.ToString()];\n}\nnode.isEnd = true;\nnode.value += val;","lineMap":{"3":9,"4":10,"5":11,"8":15,"9":16,"10":17,"11":18,"12":20,"13":22,"14":23},"statementBundles":{"5":{"startLine":11,"endLine":13},"11":{"startLine":18,"endLine":19},"12":{"startLine":20,"endLine":21}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"struct TrieNode {\n    unordered_map<string, TrieNode*> children;\n    bool is_end;\n    int value;\n\n    TrieNode() {\n        this->children = unordered_map<string, TrieNode*>{};\n        this->is_end = false;\n        this->value = 0;\n    }\n};\n\nTrieNode* node = root;\nfor (char ch : key) {\n    if (!node->children.count(string(1, ch))) {\n        node->children[string(1, ch)] = new TrieNode();\n    }\n    node = node->children.at(string(1, ch));\n}\nnode->is_end = true;\nnode->value += val;","lineMap":{"3":7,"4":8,"5":9,"8":13,"9":14,"10":15,"11":16,"12":18,"13":20,"14":21},"statementBundles":{"5":{"startLine":9,"endLine":11},"11":{"startLine":16,"endLine":17},"12":{"startLine":18,"endLine":19}}}}}},{"id":"edge-intro","kind":"info","chapter":"Edge cases","eyebrow":"Stress the idea","title":"Which inputs could bend the prefix sum?","workspacePanel":"visualizer","body":["The subtree sum was built for the common case, where the prefix lands on a node with keys hanging below it. Two inputs push on its boundaries and are worth tracing before trusting it.","First, a query prefix longer than any stored key that matches it, so the walk may run past where the keys stop. Second, a stored key that is also the start of a longer key, so one node both ends a key and continues toward others. The trie below has \"a\" worth 1 and \"ab\" worth 3, with \"a\" both a stored key and the start of \"ab\"."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-state","state":{"graph":{"nodes":[{"id":"a","label":"a=1"},{"id":"ab","label":"b=3"}],"edges":[["a","ab"]],"visited":["a","ab"]}}}]}},{"id":"edge-missing-prefix","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the idea","title":"What should sum return for a prefix no key starts with?","workspacePanel":"visualizer","summary":"Only \"trace\"=7 is stored, and the query is sum(\"tracer\").","options":[{"id":"zero","label":"0, because the prefix walk falls off the tree before it finishes","rationale":"Walking t, r, a, c, e reaches \"trace\", but the next character r has no child, since nothing extends past \"trace\". The walk cannot reach a prefix node, so no subtree exists to sum and the answer is 0. The miss must stop the walk rather than wander into a node that is not there.","isCorrect":true},{"id":"seven","label":"7, because \"trace\" is the closest stored key","rationale":"sum(\"tracer\") asks for keys that begin with \"tracer\", and \"trace\" does not, since it is shorter and stops early. A prefix longer than every stored key has no keys below it, so the total is 0.","isCorrect":false},{"id":"error","label":"An error, since the walk runs out of nodes","rationale":"Running out of child links is the normal way to learn a prefix is absent. The missing child is the signal to stop and return 0, which the code must handle rather than treat as a crash.","isCorrect":false}],"answer":"0. The walk follows \"trace\" but then needs an r child to continue to \"tracer\", and there is none. A missing child means no stored key begins with the prefix, so there is no subtree to sum and the answer is 0.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"missing-state","state":{"graph":{"nodes":[{"id":"t","label":"t"},{"id":"tr","label":"r"},{"id":"tra","label":"a"},{"id":"trac","label":"c"},{"id":"trace","label":"e=7"},{"id":"tracer","label":"r? missing"}],"edges":[["t","tr"],["tr","tra"],["tra","trac"],["trac","trace"],["trace","tracer"]],"current":"tracer","visited":["t","tr","tra","trac","trace"],"activeEdges":[["trace","tracer"]]}}}]}},{"id":"edge-key-is-prefix","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the idea","title":"When a key sits on the path to another, does its value still count?","workspacePanel":"visualizer","summary":"\"a\"=1 ends on a node that \"ab\"=3 also passes through on its way down. The query is sum(\"a\").","options":[{"id":"both","label":"Yes, the prefix node's own value and every descendant value both count, so the total is 4","rationale":"sum(\"a\") walks to the \"a\" node and adds every value in its subtree, including the value sitting on the prefix node itself. \"a\" is worth 1 there, and \"ab\" worth 3 hangs below, so the subtree total is 1 + 3 = 4. A key that is also a prefix is just a value-carrying node with more nodes beneath it.","isCorrect":true},{"id":"descendants-only","label":"No, only the keys strictly below the prefix node count, so the total is 3","rationale":"Skipping the prefix node's own value drops \"a\" itself, which is a stored key beginning with \"a\". The subtree sum must include the value on the starting node, or any key equal to the prefix vanishes from its own total.","isCorrect":false},{"id":"exact-only","label":"No, only the exact key \"a\" counts, so the total is 1","rationale":"That answers sum as if it were an exact lookup. sum gathers every key beginning with \"a\", and \"ab\" begins with \"a\" too, so its 3 must be added to \"a\"'s own 1.","isCorrect":false}],"answer":"Yes, both count, for a total of 4. The walk reaches the \"a\" node, which carries 1 as a stored key, and its subtree also holds \"ab\" worth 3. Summing the prefix node's own value together with every descendant gives 1 + 3 = 4.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"key-prefix-state","state":{"graph":{"nodes":[{"id":"a","label":"a=1"},{"id":"ab","label":"b=3"}],"edges":[["a","ab"]],"current":"a","highlighted":["ab"],"visited":["a","ab"]}}}]}},{"id":"ready-to-code","kind":"info","chapter":"Code","eyebrow":"Get ready to code","title":"Turn the subtree rule into code","workspacePanel":"visualizer","summary":"Two things to keep straight: a repeated key overwrites its terminal value, and a prefix's total includes the prefix node's own value.","body":["Give each node a small map from character to child and a stored value, and start the trie with one empty root that persists across operations. Insert walks the key, following a child when the character is there and creating one when it is not, then writes the value onto the node it ends on, replacing whatever was there.","sum walks the prefix the same way and stops at 0 the moment a character has no child. Once it reaches the prefix node, it gathers every value in that subtree, the node's own value plus the totals of all its children, and returns the sum. The trie below holds \"apple\"=3 and \"app\"=2 under the shared \"ap\" path you will build."],"ctaLabel":"Start coding","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"graph":{"nodes":[{"id":"a","label":"a"},{"id":"ap","label":"p"},{"id":"app","label":"p=2"},{"id":"appl","label":"l"},{"id":"apple","label":"e=3"}],"edges":[["a","ap"],["ap","app"],["app","appl"],["appl","apple"]],"visited":["app","apple"]}}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the trie","eyebrow":"Code the rule","summary":"Now build the trie: define a node that holds child links and a value, create the root, insert each key by walking or growing its path and writing the value where it ends, then for a query walk the prefix and stop at 0 on a missing child, total the subtree below it, and return that sum.","workspacePanel":"code","checkpoints":[{"id":"node-class","title":"Create trie nodes","description":"Store child links and a terminal value on each trie node.","commonMistakes":["Using one global value instead of terminal node values","Forgetting child links"],"hint":"Each node needs child links, an end marker, and a stored value.","semanticSpec":{"intent":"Define the node state used by the trie.","doneWhen":"A node constructor initializes child links and terminal state.","shouldFailWhen":"This step should fail if nodes do not own child-link state.","roles":["trie node","children","terminal value"],"mustProve":["Trie node state is initialized in a constructor."],"mustNotAccept":["Representing the trie as a flat map only."],"equivalentVariants":["Use a dictionary/map of child links and any terminal payload state."],"proofSnippets":[{"id":"py-map-sum-node-class","language":"typescript","code":"class TrieNode {\n  children: Record<string, TrieNode>;\n  isEnd: boolean;\n\n  constructor() {\n    const childMap: Record<string, TrieNode> = {};\n    const terminal = false;\n    this.children = childMap;\n    this.isEnd = terminal;\n  }\n}"}]},"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","description":"Create the root trie node when `MapSum` is constructed.","commonMistakes":["Creating a new root inside every operation","Leaving the root uninitialized"],"hint":"The root must persist across insert and sum operations.","semanticSpec":{"intent":"Initialize persistent trie root state for the operation class.","doneWhen":"The constructor stores a root trie node on the instance.","shouldFailWhen":"This step should fail if the root is local to only one method.","roles":["constructor","root node","persistent state"],"mustProve":["A trie root is initialized by the class constructor."],"mustNotAccept":["A root created only inside `insert` or `sum`."],"equivalentVariants":["Use `root`, `head`, or another persistent field for the trie root."],"proofSnippets":[{"id":"py-map-sum-trie-root","language":"typescript","code":"class TrieNode {\n  children: Record<string, TrieNode>;\n  isEnd: boolean;\n\n  constructor() {\n    const childMap: Record<string, TrieNode> = {};\n    const terminal = false;\n    this.children = childMap;\n    this.isEnd = terminal;\n  }\n}\n\nclass MapSum {\n  root: TrieNode;\n\n  constructor() {\n    this.root = new TrieNode();\n  }\n}"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"initializes_trie_root","scope":"trie-class","readMode":"tree-trie-value-query-v1"}]}},{"id":"insert-key","title":"Insert keys","description":"Walk or create the path for each inserted key and store its value at the terminal node.","commonMistakes":["Adding only the first character","Accumulating duplicate key values instead of replacing them"],"hint":"Create missing child nodes while walking each key.","semanticSpec":{"intent":"Insert a key by walking its characters through the trie.","doneWhen":"The insert method creates missing child links, advances through each character, and writes terminal state.","shouldFailWhen":"This step should fail if inserted keys are not represented as trie paths.","roles":["key","current node","child link","terminal value"],"mustProve":["The insert method walks the key path and writes terminal state."],"mustNotAccept":["Storing only exact keys in a flat dictionary."],"equivalentVariants":["Use map child links or fixed-size child arrays."],"proofSnippets":[{"id":"py-map-sum-insert-key","language":"typescript","code":"class TrieNode {\n  children: Record<string, TrieNode>;\n  isEnd: boolean;\n\n  constructor() {\n    this.children = {};\n    this.isEnd = false;\n  }\n}\n\nclass MapSum {\n  root: TrieNode;\n\n  constructor() {\n    this.root = new TrieNode();\n  }\n\n  insert(key: string, val: number): void {\n    let node = this.root;\n    for (const ch of key) {\n      if (!node.children[ch]) {\n        node.children[ch] = new TrieNode();\n      }\n      node = node.children[ch];\n    }\n    node.isEnd = true;\n  }\n}"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"inserts_trie_word","scope":"insert-method","readMode":"tree-trie-value-query-v1"}]}},{"id":"prefix-walk","title":"Walk the prefix path","description":"Traverse the trie along the query prefix and stop with zero if the path is missing.","commonMistakes":["Scanning every key for every prefix","Ignoring missing child links"],"hint":"A missing child during prefix traversal means no key can match.","semanticSpec":{"intent":"Use trie child links to decide whether a prefix path exists.","doneWhen":"The code walks prefix characters from the root and returns a miss result when a child link is absent.","shouldFailWhen":"This step should fail if prefix queries do not traverse trie links.","roles":["prefix","current node","child link","missing prefix"],"mustProve":["The code advances through child links for prefix characters."],"mustNotAccept":["Checking prefixes only by string slicing stored keys."],"equivalentVariants":["Use a boolean prefix helper that `sum` calls before descending to the prefix node."],"proofSnippets":[{"id":"py-map-sum-prefix-walk","language":"typescript","code":"class TrieNode {\n  children: Record<string, TrieNode>;\n  isEnd: boolean;\n\n  constructor() {\n    this.children = {};\n    this.isEnd = false;\n  }\n}\n\nclass MapSum {\n  root: TrieNode;\n\n  constructor() {\n    this.root = new TrieNode();\n  }\n\n  insert(key: string, val: number): void {\n    let node = this.root;\n    for (const ch of key) {\n      if (!node.children[ch]) {\n        node.children[ch] = new TrieNode();\n      }\n      node = node.children[ch];\n    }\n    node.isEnd = true;\n  }\n\n  startsWith(prefix: string): boolean {\n    let node = this.root;\n    for (const ch of prefix) {\n      if (!node.children[ch]) {\n        return false;\n      }\n      node = node.children[ch];\n    }\n    return true;\n  }\n}"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"checks_trie_prefix","scope":"startswith-method","readMode":"tree-trie-value-query-v1"}]}},{"id":"sum-subtree","title":"Sum subtree values","description":"DFS from the prefix node and add each terminal value in that subtree.","commonMistakes":["Returning only the prefix node's own value","Skipping descendant keys"],"hint":"Every descendant of the prefix node represents a key with that prefix.","semanticSpec":{"intent":"Accumulate values across the prefix subtree.","doneWhen":"A traversal accumulates each child subtree's total into a running total.","shouldFailWhen":"This step should fail if descendant values are never added.","roles":["subtree node","child node","running total"],"mustProve":["The code additively updates a total while traversing child nodes."],"mustNotAccept":["Returning only a boolean prefix existence result."],"equivalentVariants":["Use recursive DFS or an explicit stack to visit child nodes."],"proofSnippets":[{"id":"py-map-sum-subtree","language":"python","code":"class TrieNode:\n    def __init__(self):\n        self.children = {}\n        self.is_end = False\n        self.value = 0\n\nclass MapSum:\n    def __init__(self):\n        self.root = TrieNode()\n\n    def insert(self, key: str, val: int) -> None:\n        node = self.root\n        for char in key:\n            if char not in node.children:\n                node.children[char] = TrieNode()\n            node = node.children[char]\n        node.is_end = True\n        node.value = val\n\n    def startsWith(self, prefix: str) -> bool:\n        node = self.root\n        for char in prefix:\n            if char not in node.children:\n                return False\n            node = node.children[char]\n        return True\n\n    def sum(self, prefix: str) -> int:\n        if not self.startsWith(prefix):\n            return 0\n        node = self.root\n        for char in prefix:\n            node = node.children[char]\n\n        def dfs(cur: TrieNode) -> int:\n            total = cur.value\n            for child in cur.children.values():\n                total += dfs(child)"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"additively_updates_accumulator","scope":"update-total","readMode":"array-scan-value-query-v1"}]}},{"id":"return-total","title":"Return the prefix total","description":"Return the accumulated total for the prefix subtree.","commonMistakes":["Returning the trie node","Returning the prefix string"],"hint":"The DFS total is the answer for `sum(prefix)`.","semanticSpec":{"intent":"Return the accumulated subtree total as the query answer.","doneWhen":"The `sum` operation returns the numeric total produced from the prefix subtree.","shouldFailWhen":"This step should fail if `sum` returns a node, string, or boolean.","roles":["accumulated total","terminal return"],"mustProve":["The terminal return is the accumulator value."],"mustNotAccept":["Returning the root or prefix node object."],"equivalentVariants":["Return the recursive DFS result or an iteratively accumulated total."],"proofSnippets":[{"id":"py-map-sum-return-total","language":"python","code":"class TrieNode:\n    def __init__(self):\n        self.children = {}\n        self.is_end = False\n        self.value = 0\n\nclass MapSum:\n    def __init__(self):\n        self.root = TrieNode()\n\n    def insert(self, key: str, val: int) -> None:\n        node = self.root\n        for char in key:\n            if char not in node.children:\n                node.children[char] = TrieNode()\n            node = node.children[char]\n        node.is_end = True\n        node.value = val\n\n    def startsWith(self, prefix: str) -> bool:\n        node = self.root\n        for char in prefix:\n            if char not in node.children:\n                return False\n            node = node.children[char]\n        return True\n\n    def sum(self, prefix: str) -> int:\n        if not self.startsWith(prefix):\n            return 0\n        node = self.root\n        for char in prefix:\n            node = node.children[char]\n\n        def dfs(cur: TrieNode) -> int:\n            total = cur.value\n            for child in cur.children.values():\n                total += dfs(child)\n            return total\n\n        return dfs(node)"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_terminal_accumulator","scope":"return-result","readMode":"array-scan-value-query-v1"}]}}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"A prefix is a node, and its sum is the total of the value subtree hanging below it.","workspacePanel":"code","body":["Keys that begin alike share their opening steps, so the store becomes a tree where each node is one character and each key is a path. The prefix you are asked about is a single node, and every key starting with that prefix lives in the subtree below it.","Each key's value sits on the node where it ends, so sum walks to the prefix node and totals that subtree, the node's own value plus every descendant. Re-inserting a key overwrites that one value rather than adding to it, which keeps every prefix that passes through honest."],"takeaways":[{"title":"A prefix maps to a subtree","body":"Because keys that share an opening share one path, sum walks the prefix and totals the subtree below it in O(P + S) over the prefix length and subtree size, instead of the flat map's O(k times L) scan of every key."},{"title":"Values live on terminal nodes","body":"Storing each key's value on the node its last character lands on lets sum(\"a\") add both \"a\"'s own value and the values of deeper keys like \"ab\", since the prefix node and its descendants are exactly the keys that begin with the prefix."},{"title":"Re-inserting overwrites, never adds","body":"A key holds one value at a time, so insert writes the new value onto its terminal node rather than adding to the old one; accumulating instead would inflate every prefix containing that key, as apple=3 then apple=2 would read 5 instead of 2."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
