Skip to content
BytePatterns

Sum of Values by Prefix

EasyTries#trie#design~20m

Problem

Design a store of string keys with integer values and two operations. put(key, value) sets the value of a key, replacing the old value if the key is already stored. total(prefix) returns the sum of the values of all keys that start with the prefix, or 0 if there are none. Both operations should cost time proportional to the length of their argument.

Examples

Input:  put("apple", 3), total("ap"), put("app", 2), total("ap"), total("apple")
Output: 3, 5, 3
Why:    after both puts, "ap" begins both keys and "apple" begins only one
Input:  put("apple", 3), put("app", 2), put("apple", 5), total("ap")
Output: 7
Why:    the second put of "apple" replaces 3 with 5 rather than adding to it
Input:  put("apple", 3), total("b")
Output: 0
Why:    edge case, no key starts with the prefix

Hints

0 / 3

Stuck on the idea rather than the code? Prefix Search covers it.