things like prefix should use Trie. I draw a picture to display this solution.
/**
Runtime: 12 ms, faster than 56.55% of Java online submissions for Map Sum Pairs.
Memory Usage: 40 MB, less than 14.29% of Java online submissions for Map Sum Pairs.
*/
class MapSum {
// for update count when insert an existed key
HashMap<String, Integer> map;
TrieNode root;
/** Initialize your data structure here. */
public MapSum() {
map = new HashMap<>();
root = new TrieNode();
}
public void insert(String key, int val) {
if (key == null) {
return;
}
// for update an existed key
int delta = val - map.getOrDefault(key, 0);
map.put(key, val);
TrieNode cur = root;
cur.count += delta;
for (char c : key.toCharArray()) {
cur.children.putIfAbsent(c, new TrieNode());
cur = cur.children.get(c);
cur.count += delta;
}
}
public int sum(String prefix) {
if (prefix == null) {
return 0;
}
TrieNode cur = root;
for (char c : prefix.toCharArray()) {
cur = cur.children.get(c);
if (cur == null) {
return 0;
}
}
return cur.count;
}
}
class TrieNode {
HashMap<Character, TrieNode> children = new HashMap<>();
int count;
}
/**
* Your MapSum object will be instantiated and called as such:
* MapSum obj = new MapSum();
* obj.insert(key,val);
* int param_2 = obj.sum(prefix);
*/