Design a MapSum data structure that supports efficient key-value storage and prefix-based sum queries. This is a common system design problem that combines the functionality of a hash map with prefix matching capabilities.
Your task: Implement the MapSum class with the following operations:
MapSum()- Initialize an empty MapSum objectinsert(key, val)- Insert or update a key-value pair. If the key already exists, override the old valuesum(prefix)- Return the sum of all values whose keys start with the given prefix
Example scenario: Imagine a word frequency counter where you can query the total frequency of all words starting with a certain prefix - like finding the sum of frequencies for all words starting with "app" (apple, application, approach, etc.).
The challenge is to balance the efficiency of both insertion and prefix sum operations.
Input & Output
Visualization
Time & Space Complexity
Both insert and sum operations traverse the Trie depth equal to key/prefix length
Trie can have up to ALPHABET_SIZE children per node, with N keys of average length M
Constraints
- 1 โค key.length, prefix.length โค 50
- key and prefix consist of only lowercase English letters
- 1 โค val โค 1000
- At most 50 calls will be made to insert and sum