#677
Map Sum Pairs
specialist · 765 · lc medium +31 · 57.1% accepted · 1,732 likes · top 52%
Description
Design a key-value store that supports prefix-based sum queries.
Implement the MapSum class:
- MapSum() Creates the MapSum object.
- void insert(String key, int val) Associates key with val. If key already exists, its value is updated.
- int sum(string prefix) Returns the sum of all values whose corresponding key begins with prefix.
Example 1:
Input
["MapSum", "insert", "sum", "insert", "sum"]
[[], ["apple", 3], ["ap"], ["app", 2], ["ap"]]
Output
[null, null, 3, null, 5]
Example 2:
Explanation
MapSum mapSum = new MapSum();
mapSum.insert("apple", 3);
mapSum.sum("ap"); // return 3 (apple = 3)
mapSum.insert("app", 2);
mapSum.sum("ap"); // return 5 (apple + app = 3 + 2 = 5)
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16