Map Sum Pairs

Medium · Tries · Hash Table · String · Design · Trie

Problem

Design a map with string keys that can quickly total the values of all keys sharing a prefix.

Implement MapSum:

Tests replay a call sequence: the first entry names the class and its constructor arguments, each later entry is a method with its arguments, and calls that return nothing report None.

Examples

Input: ops = ["MapSum","insert","insert","sum","insert","sum"], args = [[],["pen",4],["pencil",6],["pen"],["pen",1],["pen"]]
Output: [None, None, None, 10, None, 7]

Both keys start with pen. Replacing pen's value with 1 changes the total to 1 + 6.

Input: ops = ["MapSum","insert","sum","sum"], args = [[],["star",9],["st"],["sp"]]
Output: [None, None, 9, 0]

No key starts with sp, so its total is 0.

Constraints

Approaches

Follow-up

What if keys were grouped by their ending, or you counted words with removals instead of summing values? See the use cases “Total by suffix” and “Count words by prefix, with removals”.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…