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
.
Example 1:
Input ["MapSum", "insert", "sum", "insert", "sum"] [[], ["apple", 3], ["ap"], ["app", 2], ["ap"]] Output [null, null, 3, null, 5] 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)
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
.
Companies:
Akuna Capital
Related Topics:
Hash Table, String, Design, Trie
// OJ: https://leetcode.com/problems/map-sum-pairs/
// Author: github.com/lzl124631x
// Time:
// MapSum: O(1)
// insert: O(WlogN) where W is word length
// sum: O(NW)
// Space: O(NW)
class MapSum {
private:
map<string, int> m;
public:
MapSum() {}
void insert(string key, int val) {
m[key] = val;
}
int sum(string prefix) {
int sum = 0;
for (auto start = m.lower_bound(prefix); start != m.end(); ++start) {
if (start->first.compare(0, prefix.size(), prefix) != 0) break;
sum += start->second;
}
return sum;
}
};
// OJ: https://leetcode.com/problems/map-sum-pairs/
// Author: github.com/lzl124631x
// Time:
// MapSum: O(1)
// insert: O(W) where W is word length
// sum: O(W)
// Space: O(NW)
struct TrieNode {
TrieNode *next[26] = {};
int sum = 0;
};
class MapSum {
TrieNode root;
unordered_map<string, int> m;
public:
MapSum() {}
void insert(string key, int val) {
int diff = val;
if (m.count(key)) diff = val - m[key];
m[key] = val;
auto node = &root;
for (char c : key) {
if (!node->next[c - 'a']) node->next[c - 'a'] = new TrieNode();
node = node->next[c - 'a'];
node->sum += diff;
}
}
int sum(string prefix) {
auto node = &root;
for (char c : prefix) {
node = node->next[c - 'a'];
if (!node) return 0;
}
return node->sum;
}
};