LeetCode #677 Medium

Map Sum Pairs

Map Sum Pairs is LeetCode 677 (Medium). Design a class MapSum with two methods:

  • insert(key, val) stores the pair. If key is already there, its old value is replaced, not added to.
  • sum(prefix) returns the total of the values of every key that starts with prefix.

Keys and prefixes are lowercase words of up to 50 letters, and there are at most 50 calls in total.

Constraints
  • 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.
triehash-tabledesign
Open on LeetCode ↗
02

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.

How to spot this pattern

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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1class TrieNode:
▶2 def __init__(self):
▶3 self.children = {}
▶4 self.total = 0
▶5 
▶6 
▶7class MapSum:
▶8 def __init__(self):
▶9 self.root = TrieNode()
▶10 self.values = {}
▶11 
▶12 def insert(self, key: str, val: int) -> None:
▶13 delta = val - self.values.get(key, 0)
▶14 self.values[key] = val
▶15 node = self.root
▶16 for ch in key:
▶17 if ch not in node.children:
▶18 node.children[ch] = TrieNode()
▶19 node = node.children[ch]
▶20 node.total += delta
▶21 
▶22 def sum(self, prefix: str) -> int:
▶23 node = self.root
▶24 for ch in prefix:
▶25 if ch not in node.children:
▶26 return 0
▶27 node = node.children[ch]
▶28 return node.total
rootoperationnone yetchangevaluesemptyempty trie, no values yet
operations4
Each trie node will hold one number: the sum of the current values of every key that passes through it. A separate table remembers each key's current value, so a repeated insert can work out how much to change.
rootoperationinsert apple, 3change3−0=+3valuesapple3apple is new → add 3 along its path
keyapple
old value0not in the table
change+3
apple is not in the table yet, so its old value counts as 0 and the change is the full 3. The table now records apple = 3.
roota3operationinsert apple, 3change3−0=+3valuesapple3new node a: total 0 → 3
prefixa
node total3new node, +3
No node for a yet, so it is created with total 0. Every key that starts with a passes through this node, and apple is one of them, so its total moves by +3 to 3.
roota3p3operationinsert apple, 3change3−0=+3valuesapple3new node p: total 0 → 3
prefixap
node total3new node, +3
No node for ap yet, so it is created with total 0. Every key that starts with ap passes through this node, and apple is one of them, so its total moves by +3 to 3.
roota3p3p3operationinsert apple, 3change3−0=+3valuesapple3new node p: total 0 → 3
prefixapp
node total3new node, +3
No node for app yet, so it is created with total 0. Every key that starts with app passes through this node, and apple is one of them, so its total moves by +3 to 3.
roota3p3p3l3operationinsert apple, 3change3−0=+3valuesapple3new node l: total 0 → 3
prefixappl
node total3new node, +3
No node for appl yet, so it is created with total 0. Every key that starts with appl passes through this node, and apple is one of them, so its total moves by +3 to 3.
roota3p3p3l3e3operationinsert apple, 3change3−0=+3valuesapple3new node e: total 0 → 3
prefixapple
node total3new node, +3
No node for apple yet, so it is created with total 0. Every key that starts with apple passes through this node, and apple is one of them, so its total moves by +3 to 3.
roota3p3p3l3e3operationsum apanswer?valuesapple3follow a (1 of 2)
prefixap
walkeda
Follow the child for a. The prefix is not used up yet, so keep walking.
roota3p3p3l3e3operationsum apanswer?valuesapple3follow p (2 of 2)
prefixap
walkedap
Follow the child for p. That is the last letter of the prefix, so this node stands for every key that starts with ap.
roota3p3p3l3e3operationsum apanswer3valuesapple3sum of ap: 3, read off one node
sum(ap)3
The node for ap already holds the total of every key below it, so the answer is read directly: 3. No key under it has to be visited.
roota3p3p3l3e3operationinsert app, 2change2−0=+2valuesapple3app2app is new → add 2 along its path
keyapp
old value0not in the table
change+2
app is not in the table yet, so its old value counts as 0 and the change is the full 2. The table now records app = 2.
roota5p3p3l3e3operationinsert app, 2change2−0=+2valuesapple3app2a: total 3 → 5
prefixa
node total5was 3, +2
Every key that starts with a passes through this node, and app is one of them, so its total moves by +2 to 5.
roota5p5p3l3e3operationinsert app, 2change2−0=+2valuesapple3app2p: total 3 → 5
prefixap
node total5was 3, +2
Every key that starts with ap passes through this node, and app is one of them, so its total moves by +2 to 5.
roota5p5p5l3e3operationinsert app, 2change2−0=+2valuesapple3app2p: total 3 → 5
prefixapp
node total5was 3, +2
Every key that starts with app passes through this node, and app is one of them, so its total moves by +2 to 5.
roota5p5p5l3e3operationsum apanswer?valuesapple3app2follow a (1 of 2)
prefixap
walkeda
Follow the child for a. The prefix is not used up yet, so keep walking.
roota5p5p5l3e3operationsum apanswer?valuesapple3app2follow p (2 of 2)
prefixap
walkedap
Follow the child for p. That is the last letter of the prefix, so this node stands for every key that starts with ap.
roota5p5p5l3e3operationsum apanswer5valuesapple3app2sum of ap: 5, read off one node
sum(ap)5
The node for ap already holds the total of every key below it, so the answer is read directly: 5. No key under it has to be visited.
05

Common pitfalls

Adding the new value on a repeated insert

✗ Wrong
for ch in key:
    ...
    node.total += val
✓ Right
delta = val - self.values.get(key, 0)
for ch in key:
    ...
    node.total += delta

The 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

✗ Wrong
self.values[key] = val
delta = val - self.values.get(key, 0)
✓ Right
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

✗ Wrong
node = walk_to(key)
node.total += delta
✓ Right
for ch in key:
    node = node.children[ch]
    node.total += delta

A 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.

06

Edge cases

A prefix that matches no key

The walk meets a missing child and returns 0 straight away. insert("cat", 2) then sum("cb") gives 0.

The prefix is a whole key

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.

07

Complexity

Time
O(L) per call
Space
O(total letters inserted)
L is the length of the key or prefix. Each call walks at most L nodes and does one table lookup. The trie holds at most one node per inserted letter, and the table holds one entry per distinct key.
08

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.