Problem Statement
Map Sum Pairs
We need to build a little map that does two things. First, insert: store a word along with a number for it. If you insert the same word again, the new number replaces the old one. Second, sum: given the start of a word (a prefix), add up the numbers of every stored word that begins with those letters. A prefix is just the first few letters of a word, like "ap" is a prefix of "apple" and "app". So if "apple" has 3 and "app" has 2, then asking for the sum of prefix "ap" gives 5, because both words start with "ap". The tool that makes this fast is a trie. A trie is like a tree of letters: you spell words out one letter at a time, and words that share a beginning share the same path. We will store running totals on the nodes of that tree so the prefix sum is ready to read.
Signals to notice
Brute force first
Store key-value pairs in a map, for sum iterate all keys checking prefix — per sum query. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.
The key insight
Trie where each node stores the cumulative sum of all values passing through it. On insert, update the delta (new value - old value) along the path. Sum query = walk to the prefix node and return its accumulated sum. per operation. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.
Trace it on ops: insert("apple",3), sum("ap"), insert("app",2), sum("ap")
insert("apple",3): delta=3-0=3; walk a->p->p->l->e, each node.val += 3
trie node vals now: a=3, ap=3, app=3, appl=3, apple=3
sum("ap"): walk a->p, return node.val at 'ap' = 3 -> output 3
insert("app",2): delta=2-0=2; walk a->p->p, each node.val += 2
trie node vals now: a=5, ap=5, app=5, appl=3, apple=3
sum("ap"): walk a->p, return node.val at 'ap' = 5 -> output 5
returned results: [null, null, 3, null, 5]What must stay true
Each trie node stores the sum of values for all keys that pass through that node. This means the sum for any prefix is available at the node where the prefix ends — no iteration needed. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.
Shape of the loop
insert(key, val): delta = val - oldMap.get(key, 0); oldMap[key] = val cur = root for c in key: cur = cur.children[c] (create if absent); cur.val += delta sum(prefix): cur = root; for c in prefix: if missing return 0; cur = cur.children[c] return cur.val
Pseudocode only — the full worked solution lives in the Solution tab.
Easy way to go wrong
Not handling updates — when a key is re-inserted with a new value, you must subtract the old value and add the new one along the path. Track the old value in a separate map. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.