Solution: Map Sum Pairs
Explore how to implement a Map Sum Pairs data structure using a trie to handle key-value insertions and prefix sum queries efficiently. Understand updating key values and maintaining cumulative sums for prefix-based searches, preparing you for solving similar trie-based coding problems.
We'll cover the following...
Statement
Design a data structure that supports the following operations:
Insert a key-value pair:
Each key is a string, and each value is an integer.
If the key already exists, update its value to (overriding the previous value).
Return the prefix sum:
Given a string,
prefix, return the total sum of all values associated with keys that start with this prefix.
To accomplish this, implement a class MapSum:
Constructor: Initializes the object.
void insert (String key, int val): Inserts the key-value pair into the data structure. If the key already exists, its value is updated to the new one.
int sum (String prefix): Returns the total sum of values for all keys that begin with the specified prefix.
Constraints:
key.length,prefix.length...