Practice › Trie
Map Sum Pairs
Medium · Trie · Asked at Google, Amazon, Akuna Capital
Process q operations on a map from words to numbers:
insert key val— set the value ofkeytoval(replacing any earlier value of that key).sum prefix— print the sum of the values of all keys that start withprefix.
Input
First line: q. Next q lines: one operation each.
Output
One line for each sum operation.
Constraints
- 1 ≤ q ≤ 10^5
- 1 ≤ word length ≤ 50
- 1 ≤ val ≤ 10^4
- only lowercase letters
Store at every trie node the sum of the values of the keys below it. On insert, add the difference (new value − old value) along the path — remember old values in a hash map.
Example 1
Input
4 insert apple 3 sum ap insert app 2 sum ap
Output
3 5
Example 2
Input
4 insert a 5 insert a 1 sum a sum b
Output
1 0
Hints
- Let every trie node store the total value of all keys that pass through it.
- Then a sum query is just: walk to the prefix node and read its total.
- When a key is inserted again, only the difference from its old value should be added.
Approach
Keep a hash map key → current value. On insert key val, compute delta = val − old value (0 if new), store val, and add delta to the total of every node along the key's path (creating nodes as needed). On sum prefix, walk the prefix; print 0 if it falls off the trie, else the node's total. Both operations cost O(length).
Complexity: O(length) per operation · O(total letters inserted) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int q;
cin >> q;
vector<array<int, 26>> nxt(1);
nxt[0].fill(-1);
vector<long long> total(1, 0);
unordered_map<string, long long> value;
while (q--) {
string op, key;
cin >> op >> key;
if (op == "insert") {
long long val;
cin >> val;
long long delta = val - value[key];
value[key] = val;
int cur = 0;
total[0] += delta;
for (char c : key) {
int x = c - 'a';
if (nxt[cur][x] == -1) {
nxt[cur][x] = nxt.size();
nxt.emplace_back();
nxt.back().fill(-1);
total.push_back(0);
}
cur = nxt[cur][x];
total[cur] += delta;
}
} else {
int cur = 0;
for (char c : key) {
cur = nxt[cur][c - 'a'];
if (cur == -1) break;
}
cout << (cur == -1 ? 0 : total[cur]) << "\n";
}
}
return 0;
}Python solution
import sys
lines = sys.stdin.read().split("\n")
q = int(lines[0])
trie = {"#": 0}
value = {}
out = []
for line in lines[1 : 1 + q]:
parts = line.split()
if parts[0] == "insert":
key, val = parts[1], int(parts[2])
delta = val - value.get(key, 0)
value[key] = val
node = trie
for c in key:
node = node.setdefault(c, {"#": 0})
node["#"] += delta
else:
node = trie
for c in parts[1]:
node = node.get(c)
if node is None:
break
out.append(node["#"] if node else 0)
print("\n".join(map(str, out)))Java solution
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int q = Integer.parseInt(br.readLine().trim());
List<int[]> nxt = new ArrayList<>();
List<Long> total = new ArrayList<>();
int[] root = new int[26];
Arrays.fill(root, -1);
nxt.add(root);
total.add(0L);
HashMap<String, Long> value = new HashMap<>();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < q; i++) {
String[] p = br.readLine().trim().split("\\s+");
if (p[0].equals("insert")) {
long val = Long.parseLong(p[2]);
long delta = val - value.getOrDefault(p[1], 0L);
value.put(p[1], val);
int cur = 0;
for (char c : p[1].toCharArray()) {
int x = c - 'a';
if (nxt.get(cur)[x] == -1) {
int[] fresh = new int[26];
Arrays.fill(fresh, -1);
nxt.add(fresh);
total.add(0L);
nxt.get(cur)[x] = nxt.size() - 1;
}
cur = nxt.get(cur)[x];
total.set(cur, total.get(cur) + delta);
}
} else {
int cur = 0;
for (char c : p[1].toCharArray()) {
cur = nxt.get(cur)[c - 'a'];
if (cur == -1) break;
}
sb.append(cur == -1 ? 0 : total.get(cur)).append('\n');
}
}
System.out.print(sb);
}
}