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), sets the key's value, replacing any value the key had before. The second, sum(prefix), returns the total of the values of all keys that start with prefix. Keys and prefixes are made of the lowercase letters a to z.

Example 1
Input: insert("apple", 3), sum("ap"), insert("app", 2), sum("ap")
Output: 3, 5
Example 2
Input: insert("apple", 3), insert("app", 2), insert("apple", 1), sum("ap")
Output: 3
Explanation: the second insert of "apple" replaces 3 with 1.
Solution

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 without checking every word in the list against the prefix on every call?

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.

Two rows show the trie for apple and app, one node per letter, with the total of the keys that pass through each node. In the first row, with apple = 3 and app = 2, the node for ap holds 5. In the second row, after apple is set to 1, every node on its path has dropped by 2 and the node for ap holds 3.

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") only has to walk two links and read one number. In the first row that number is 5, which is 3 for apple plus 2 for app. The two nodes after the links l and e hold only 3, because only apple goes on past app.

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 insert updates the totals, and how sum finds the node for a prefix.

The plain approach: a map and a loop

Why not keep the keys in a HashMap from key to value, and have sum loop over all of them? That works, and insert becomes a single put. But every sum then reads every stored key and compares its start with the prefix, so with thousands of keys each call does thousands of comparisons. The trie moves that work into insert, which touches only the nodes of one key.

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', which is 15, and holds the next node, or null when no key continues with that letter. Next to the array, the node keeps its total in an int field.

Updating the totals on insert

What should insert add to each node on the path? A new key adds its whole value. A key that already has a value adds only the change, as apple's -2 in the second row of the picture showed. To know the old value, the class keeps a HashMap from each key to its current value, and a key not in it counts as 0. One formula then covers both cases: the new value minus the old one.

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("") can read it there.

Finding the node for a prefix

What if no key starts with the prefix? Walking down from the root, sum follows one link per letter of the prefix. If a slot it needs is null, the path breaks off, no stored key has that start, and the answer is 0.

Java Solution

The class has these parts:

  • Node: one node of the trie, with the array next of 26 links and the field sum, the total of the keys that pass through it.
  • root: the node every key starts from.
  • values: a HashMap from each key to its current value, used to work out the change.
  • insert: computes the change in a variable named delta, then walks the key's letters from the root, creating missing nodes and adding delta to every node on the way, the root included.
  • sum: walks the prefix's letters and returns the total on the node where it stops, or 0 if a link is missing.

The main method runs both examples, each on a new object, then asks the second object about the keys apple and app, two prefixes no key starts with, the empty prefix, and a repeated insert with the same value.

Java
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:

Output
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 node where app ends also lies on apple's path, so its total is app's 2 plus apple's 1.

The line sum("apple") = 1 holds apple alone, since no other key reaches its last node. The prefix b gives 0 because the root has no link for b, and applex gives 0 because the path ends at e. For the empty prefix, sum("") = 3: the loop never runs and the root's total comes back, which is why insert adds delta to the root too. On the last line, inserting app with 2 again gives a change of 0, and the total for "ap" stays 3.

Why not add val to each node instead of delta? Then a replaced key is counted twice. With that one change, Example 2 prints sum("ap") = 6, because apple's old 3 and new 1 are both in the totals, next to app's 2.

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 insert the map lookup and update hash the key's L letters too.
  • 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 values adds one entry per key.

For a trie that stores words and answers whether a word or a prefix is present, see Implement Trie.