You are tasked with implementing the MapSum
class, which supports the following two methods:
void insert(String key, int val)
: Inserts the key-value pair into the map. If the key already exists, the original key-value pair will be overridden to the new one.int sum(String prefix)
: Returns the sum of all the pairs’ values whose keys start with the specified prefix.Q: Can the keys contain non-alphabetic characters? A: For this problem, we can assume keys are strings consisting of lowercase English letters.
Q: Could there be any constraints on the length of keys or the number of key-value pairs? A: The problem does not specify constraints. We can assume typical constraints for such problems where the input size is manageable within memory limits of typical competitive programming environments.
Q: How should we handle an insert operation with a key that already exists? A: If the key already exists, the existing value must be replaced with the new value provided during the insert operation.
HashMap
to store the key-value pairs.Trie
(prefix tree) data structure. Each node in the Trie will carry:
Map
to its children nodes.HashMap
.import java.util.HashMap;
import java.util.Map;
class MapSum {
class TrieNode {
Map<Character, TrieNode> children = new HashMap<>();
int value = 0;
}
private TrieNode root;
private Map<String, Integer> map;
public MapSum() {
root = new TrieNode();
map = new HashMap<>();
}
public void insert(String key, int val) {
int delta = val - map.getOrDefault(key, 0);
map.put(key, val);
TrieNode node = root;
for (char c : key.toCharArray()) {
node = node.children.computeIfAbsent(c, k -> new TrieNode());
node.value += delta;
}
}
public int sum(String prefix) {
TrieNode node = root;
for (char c : prefix.toCharArray()) {
node = node.children.get(c);
if (node == null) {
return 0;
}
}
return node.value;
}
public static void main(String[] args) {
MapSum mapSum = new MapSum();
mapSum.insert("apple", 3);
System.out.println(mapSum.sum("ap")); // Output: 3
mapSum.insert("app", 2);
System.out.println(mapSum.sum("ap")); // Output: 5
}
}
O(L)
where L
is the length of the key. This is because we traverse the key to update the Trie and HashMap
.O(P)
where P
is the length of the prefix. We only traverse the Trie nodes up to the length of the prefix.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?