Map Sum Pairs
Map Sum Pairs is LeetCode 677 (Medium). Design a class MapSum with two methods:
insert(key, val)stores the pair. Ifkeyis already there, its old value is replaced, not added to.sum(prefix)returns the total of the values of every key that starts withprefix.
Keys and prefixes are lowercase words of up to 50 letters, and there are at most 50 calls in total.
- 1 <= key.length, prefix.length <= 50
- key and prefix consist of only lowercase English letters.
- 1 <= val <= 1000
- At most 50 calls will be made to insert and sum.
Intuition
Every key that starts with a prefix passes through the same trie node: the node for that prefix. So give each node a running total of the values of the keys that pass through it, and sum(prefix) becomes a walk down the prefix followed by reading one number.
Inserting a key adds its value to every node on its path. The one catch is the replace rule. If the key was already worth 3 and is now worth 5, its path already counts the 3, so add only the change, 5 − 3 = 2. A small hash map from key to current value supplies the old value; for a new key it is 0.
A question that adds up, counts or ranks values over every key with a given prefix is a trie whose nodes carry a summary of everything below them. The walk costs the length of the prefix, however many keys share it.
Approach
Before reading on, decide what each trie node should store so that a prefix query needs no search below it. Then decide what an insert must add when the key is already present. Aim for O(length of the key) per call.
Keep a trie and a value table
Each TrieNode has children and a total. A separate dictionary values maps each key to its current value. The trie answers prefix questions, and the table remembers what each key is worth now, which the trie alone cannot tell you.
Work out the change on insert
Compute delta = val - values.get(key, 0), then set values[key] = val. For a new key the change is the whole value. For a repeated key the nodes on its path already count the old value, so only the difference may be added.
Add the change along the key's path
Walk the key letter by letter from the root, creating any missing child, and add delta to total at every node you step on. Each of those nodes stands for a prefix of the key, so each one's sum moves by exactly the change.
Answer sum by walking the prefix
Walk the prefix letter by letter. If a letter has no child, no key starts with that prefix, so return 0. Otherwise return total of the node you stop on: it already holds the values of every key below it.
Code in Python, C++ and Java
Common pitfalls
Adding the new value on a repeated insert
for ch in key:
...
node.total += valdelta = val - self.values.get(key, 0)
for ch in key:
...
node.total += deltaThe path already counts the old value. After insert("apple", 3) and insert("apple", 2), adding the full value leaves sum("ap") at 5 instead of 2, because the problem says a repeated key replaces its value.
Updating the table before reading the old value
self.values[key] = val delta = val - self.values.get(key, 0)
delta = val - self.values.get(key, 0) self.values[key] = val
Written in this order, the lookup reads the value just stored, so delta is always 0. After insert("a", 3) the trie never changes and sum("a") returns 0.
Adding only at the node where the key ends
node = walk_to(key) node.total += delta
for ch in key:
node = node.children[ch]
node.total += deltaA shorter prefix would then miss the key. After insert("apple", 3), sum("ap") must already be 3, so every node on the path has to move, not just the last one.
Edge cases
The walk meets a missing child and returns 0 straight away. insert("cat", 2) then sum("cb") gives 0.
sum("apple") after insert("apple", 3) stops on the node for the last letter, whose total includes apple itself, so it returns 3. A key counts as starting with itself.
Complexity
Map Sum Pairs FAQ
Is a trie needed when there are only 50 calls?
Not for passing. With at most 50 keys, keeping a plain dictionary and summing every key that starts with the prefix is fast enough. The trie is the answer interviewers expect, because it keeps each call at O(L) however many keys there are.
Can a hash map of prefixes replace the trie?
Yes. On insert, add the change to a map entry for every prefix of the key, and answer sum with one lookup. It is the same idea with the trie nodes replaced by prefix strings, at the cost of building L strings per insert.