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 theMapSumobject.void insert(String key, int val)Inserts thekey-valpair into the map. If thekeyalready existed, the originalkey-valuepair will be overridden to the new one.int sum(string prefix)Returns the sum of all the pairs’ value whosekeystarts with theprefix.
Examples
Example 1
| |
Constraints
1 <= key.length, prefix.length <= 50keyandprefixconsist of only lowercase English letters.1 <= val <= 1000- At most
50calls will be made toinsertandsum.
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
HashMapto 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-valuepair in theHashMap. - If the key existed before and is being updated, adjust the values stored in the
Trieto account for the difference. - Insert the
keyinto theTrie, updating the cumulative sums along the way.
- Update the
- Sum Operation:
- Traverse the
Triefrom its root to evaluate the cumulative sum for the given prefix.
- Traverse the
Code
| |
| |
Complexity
- ⏰ Time complexity:
insert:O(k)wherekis the length of the key being inserted.sum:O(p)wherepis the length of the prefix provided.
- 🧺 Space complexity:
O(n * k)for the Trie, wherenis the number of keys andkis the average key length, plus the space for theHashMap.