Problem
Design a map that allows you to do the following:
- Maps a string key to a given value.
- Returns the sum of the values that have a key with a prefix equal to a given string.
Implement the MapSum
class:
MapSum()
Initializes theMapSum
object.void insert(String key, int val)
Inserts thekey-val
pair into the map. If thekey
already existed, the originalkey-value
pair will be overridden to the new one.int sum(string prefix)
Returns the sum of all the pairs’ value whosekey
starts with theprefix
.
Examples
Example 1:
|
|
Constraints:
1 <= key.length, prefix.length <= 50
key
andprefix
consist of only lowercase English letters.1 <= val <= 1000
- At most
50
calls will be made toinsert
andsum
.
Solution
Method 1 - Using map and prefix sum
To solve the problem, we need to design a class that supports two primary operations: inserting a key-value
pair and calculating the sum of all values associated with keys that share a given prefix.
- Data Structure:
- Use a
HashMap
to store the mapping of keys to their respective values. - Use a
Trie
(prefix tree) to efficiently compute the sum of values based on prefixes.
- Use a
- Insert Operation:
- Update the
key-value
pair in theHashMap
. - If the key existed before and is being updated, adjust the values stored in the
Trie
to account for the difference. - Insert the
key
into theTrie
, updating the cumulative sums along the way.
- Update the
- Sum Operation:
- Traverse the
Trie
from its root to evaluate the cumulative sum for the given prefix.
- Traverse the
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
insert
:O(k)
wherek
is the length of the key being inserted.sum
:O(p)
wherep
is the length of the prefix provided.
- 🧺 Space complexity:
O(n * k)
for the Trie, wheren
is the number of keys andk
is the average key length, plus the space for theHashMap
.