Map Sum Pairs
MediumUpdated: Aug 2, 2025
Practice on:
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
**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 (_ap_ ple = 3)
mapSum.insert("app", 2);
mapSum.sum("ap"); // return 5 (_ap_ ple + _ap_ p = 3 + 2 = 5)
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
Java
class Solution {
static class MapSum {
private final Map<String, Integer> map;
private final TrieNode trie;
public MapSum() {
map = new HashMap<>();
trie = new TrieNode();
}
public void insert(String key, int val) {
int diff = val - map.getOrDefault(key, 0);
map.put(key, val);
TrieNode node = trie;
for (char ch : key.toCharArray()) {
node.children.putIfAbsent(ch, new TrieNode());
node = node.children.get(ch);
node.sum += diff;
}
}
public int sum(String prefix) {
TrieNode node = trie;
for (char ch : prefix.toCharArray()) {
if (!node.children.containsKey(ch)) {
return 0;
}
node = node.children.get(ch);
}
return node.sum;
}
static class TrieNode {
Map<Character, TrieNode> children;
int sum;
TrieNode() {
children = new HashMap<>();
sum = 0;
}
}
}
}
Python
class Solution:
class MapSum:
def __init__(self) -> None:
self.map: Dict[str, int] = {}
self.trie: Dict = {}
def insert(self, key: str, val: int) -> None:
diff = val - self.map.get(key, 0)
self.map[key] = val
node = self.trie
for ch in key:
if ch not in node:
node[ch] = {"sum": 0, "next": {}}
node[ch]["sum"] += diff
node = node[ch]["next"]
def sum(self, prefix: str) -> int:
node = self.trie
for ch in prefix:
if ch not in node:
return 0
node = node[ch]["next"]
ans = node.get("sum", 0)
return ans
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.