Map Sum Pairs
Add up the values of all keys that start with a prefix, by keeping a running total on every node of a trie.
Write a class that stores string keys, each with an integer value, and has two methods. The first, insert(key, val)sum(prefix)prefix
Example 1
Output: 3, 5
Example 2
Output: 3
Explanation: the second insert of "apple" replaces 3 with 1.
The Idea
Suppose you keep a list of words with a number next to each, and someone keeps asking what the numbers of all words starting with "ap" add up to. In Example 1 the list first holds only apple with 3, so the answer is 3. Then app joins with 2, both words start with "ap", and the answer becomes 5.
Example 2 adds a twist. The key apple is inserted again, this time with 1. A key holds one value, so the 1 replaces the 3, and the list now reads apple 1 and app 2, which makes 3. So how do we answer sum
Look at how the two words are spelled: apple and app share their first three letters. Store them letter by letter instead, one letter on each link between small records called nodes, and the shared letters can share nodes. Look at the first row of the picture below, where each circle is a node.
The node on the left, labelled root, is where every word starts. The link marked a leads to the next node, and the link marked p to the node for "ap". A second p leads to the node labelled end of "app", drawn with a double ring because a key ends there. Two more links, l and e, lead to the end of "apple". Keys stored like this, one letter per link, with words that start alike sharing their first nodes, form a trie (said like "try").
Now the question has a neat answer. Every key that starts with "ap" passes through the node for "ap". If each node keeps the total value of the keys that pass through it, sum("ap")
The second row, headed After insert("apple", 1), shows Example 2. The value of apple changes from 3 to 1, a change of 1 - 3 = -2. Adding -2 to every node on apple's path keeps all the totals right, and the node for "ap" now holds 3, the answer Example 2 expects.
Solution Approach
Turning that idea into code means comparing it with the plain approach first, and then settling three things: how a node keeps its links, how insertsum
The plain approach: a map and a loop
Why not keep the keys in a HashMapsuminsertputsuminsert
How a node keeps its links
How does a node know which links leave it? Each node has an array of 26 slots, one for each letter from a to z. The slot for p sits at position 'p' - 'a'nullint
Updating the totals on insert
What should insertHashMap
The root gets the change as well. Every key starts with the empty prefix "", so the root's total is the sum of all values, and sum("")
Finding the node for a prefix
What if no key starts with the prefix? Walking down from the root, sumnull
Java Solution
The class has these parts:
: one node of the trie, with the arrayNode of 26 links and the fieldnext , the total of the keys that pass through it.sum : the node every key starts from.root : avalues from each key to its current value, used to work out the change.HashMap : computes the change in a variable namedinsert , then walks the key's letters from the root, creating missing nodes and addingdelta to every node on the way, the root included.delta : walks the prefix's letters and returns the total on the node where it stops, or 0 if a link is missing.sum
The main
import java.util.HashMap;
import java.util.Map;
public class MapSumPairs {
private static class Node {
Node[] next = new Node[26]; // one slot per letter, 'a' to 'z'
int sum; // total value of all keys that pass through this node
}
private final Node root = new Node();
private final Map<String, Integer> values = new HashMap<>(); // each key's current value
public void insert(String key, int val) {
int delta = val - values.getOrDefault(key, 0); // a new key: the whole value
values.put(key, val);
Node cur = root;
cur.sum += delta; // the root sits on every path
for (char ch : key.toCharArray()) {
int i = ch - 'a';
if (cur.next[i] == null) {
cur.next[i] = new Node();
}
cur = cur.next[i];
cur.sum += delta;
}
}
public int sum(String prefix) {
Node cur = root;
for (char ch : prefix.toCharArray()) {
cur = cur.next[ch - 'a'];
if (cur == null) {
return 0; // no key starts with this prefix
}
}
return cur.sum;
}
public static void main(String[] args) {
MapSumPairs first = new MapSumPairs();
first.insert("apple", 3);
System.out.println("Example 1: sum(\"ap\") = " + first.sum("ap"));
first.insert("app", 2);
System.out.println("Example 1: sum(\"ap\") = " + first.sum("ap"));
MapSumPairs second = new MapSumPairs();
second.insert("apple", 3);
second.insert("app", 2);
second.insert("apple", 1);
System.out.println("Example 2: sum(\"ap\") = " + second.sum("ap"));
System.out.println("sum(\"apple\") = " + second.sum("apple"));
System.out.println("sum(\"app\") = " + second.sum("app"));
System.out.println("sum(\"b\") = " + second.sum("b"));
System.out.println("sum(\"applex\") = " + second.sum("applex"));
System.out.println("sum(\"\") = " + second.sum(""));
second.insert("app", 2); // same value again
System.out.println("after insert(\"app\", 2) again: sum(\"ap\") = " + second.sum("ap"));
}
}
Running it prints:
Example 1: sum("ap") = 3
Example 1: sum("ap") = 5
Example 2: sum("ap") = 3
sum("apple") = 1
sum("app") = 3
sum("b") = 0
sum("applex") = 0
sum("") = 3
after insert("app", 2) again: sum("ap") = 3
Example 1 prints 3 and then 5, and Example 2 prints 3: apple's -2 was added along its path, so the old 3 is not counted. Look at sum("app") = 3
The line sum("apple") = 1sum("") = 3insertdelta
Why not add valdeltasum("ap") = 6
Complexity
Both methods walk one node per letter, so their cost depends on the length of the key or prefix, not on how many keys are stored.
- Time: O(L) per call, where L is the length of the key or prefix, because the loop follows one link per letter, and in
the map lookup and update hash the key's L letters too.insert - Space: O(26 × T), where T is the total number of letters in the distinct keys, because keys that share no starts give each letter its own node with a 26-slot array, and
adds one entry per key.values
For a trie that stores words and answers whether a word or a prefix is present, see