mediumTrieTrie

Map Sum Pairs

mediumTime: O(m)Space: O(n * m)

Signals to notice

map keys to values with prefix suminsert key-value pairssum all values with given prefix

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.

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.

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.

Trie Pattern