DSA Trie

Map Sum Pairs

Insert (key, val) and query sum of values for keys with a given prefix — trie with subtree sums.

Medium
Time O(L) per op Space O(N * L)
LeetCode
5 min read
trie design

Problem#

Design MapSum with:

  • insert(key, val) — insert/overwrite a key with value val.
  • sum(prefix) — return the sum of values for all keys starting with prefix.

Examples#

  • insert("apple", 3); sum("ap")3; insert("app", 2); sum("ap")5.
  • insert("apple", 2); sum("apple")2 (overwrite, not accumulate).

Constraints#

  • 1 <= key.length, prefix.length <= 50, 1 <= val <= 1000, up to 50 calls.

Hints#

Hint
Store full key -> val to compute the delta on overwrite; propagate the delta through the trie.

Approach#

Trie where each node stores the running sum of all values whose key passes through it. Maintain a separate unordered_map<key, value> to compute the delta when a key is re-inserted (delta = newVal - oldVal). Add delta to every node on the path.

Solution#

Map Sum Pairs
class MapSum {
struct Node {
Node* child[26]{};
int sum = 0;
};
Node* root;
unordered_map<string, int> stored;
public:
MapSum() : root(new Node()) {}
void insert(string key, int val) {
int delta = val - stored[key];
stored[key] = val;
Node* cur = root;
for (char c : key) {
int i = c - 'a';
if (!cur->child[i]) cur->child[i] = new Node();
cur = cur->child[i];
cur->sum += delta;
}
}
int sum(string prefix) {
Node* cur = root;
for (char c : prefix) {
int i = c - 'a';
if (!cur->child[i]) return 0;
cur = cur->child[i];
}
return cur->sum;
}
};

Editorial#

The delta trick handles the overwrite semantics in one pass: every node above the leaf has its old contribution subtracted and new contribution added. Each operation is O(L)sum is just a walk to the prefix node and a read.

Complexity#

  • Time: O(L) per insert / sum.
  • Space: O(N * L).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.