We use cookies for site analytics. Accept to help us understand how the site is used. See our Privacy Policy for details.
A medium trie problem, graded against 6 test cases (3 of them hidden).
A prefix tree for fast string lookup by shared prefix.
Reach for it when you see: Many words, repeated prefix queries, autocomplete, or word-search over a grid.
More Trieproblems →Put a running `total` on every trie node meaning "sum of the values of all keys passing through here". Then `sum(prefix)` is a walk down the prefix and a single read - no subtree traversal.
The hard part is not the trie, it is the overwrite semantics. If `insert` simply adds the value along the path, then re-inserting an existing key double-counts it: `insert("a", 1)` followed by `insert("a", 5)` would report 6 instead of 5.
The fix is to keep an ordinary map of `key -> current value` alongside the trie. On insert, compute `delta = newValue - (previousValue ?? 0)` and propagate the delta, not the value. For a new key the delta is the value itself; for an overwrite it is exactly the correction needed, and it works for decreases too.
This is a good example of a problem where the data structure is the easy half and the update semantics are what actually gets tested.
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
Read off this problem's own test suite, so these are the cases a submission actually has to survive.
These apply to the pattern as a whole, not just this problem.