Map Sum Pairs
Keep a running total in each trie node so the sum of all keys with a given prefix is one walk away.
The problem
Design a class MapSum. MapSum() creates an empty map. insert(key, val) stores the integer val under the string key; if key is already stored, its old value is replaced by val. sum(prefix) returns the total of the values of all stored keys that start with prefix, or 0 if no key does. A key counts as starting with itself. Keys and prefixes are lowercase and at most 50 letters long, values are between 1 and 1,000, and there are at most 50 calls.
Starter code
class MapSum:
def __init__(self):
passPublic examples
obj = MapSum() obj.insert("apple", 3) obj.sum("ap") obj.insert("app", 2) obj.sum("ap") obj.insert("apple", 2) obj.sum("ap")gives[None, None, 3, None, 5, None, 4]obj = MapSum() obj.insert("cat", 7) obj.insert("dog", 2) obj.sum("c") obj.sum("d")gives[None, None, None, 7, 2]obj = MapSum() obj.insert("a", 4) obj.insert("a", 4) obj.sum("a")gives[None, None, None, 4]
Solving it in the practice book needs an active paid plan.
Open it in the practice bookOne thought at a time.
