Coding Interview PatternsMap Sum Pairs
MediumTrie
Map Sum Pairs
Explanation & Solution
Description
Design a MapSum class that supports two operations:
insert(key, val)— Insert the key-value pair into the map. If the key already existed, the original key-value pair will be overridden to the new one.sum(prefix)— Return the sum of all the values of keys that have a prefix equal to a given prefix.
Implement the MapSum class using a trie data structure.
Input:operations = ["MapSum","insert","sum","insert","sum"], operands = [[],["apple",3],["ap"],["app",2],["ap"]]
0
MapSum
1
insert
2
sum
3
insert
4
sum
Output:[null,null,3,null,5]
0
null
1
null
2
3
3
null
4
5
Explanation:
MapSum()— Initialize the object.insert("apple", 3)— Insert key"apple"with val3.sum("ap")— Return3(apple = 3).insert("app", 2)— Insert key"app"with val2.sum("ap")— Return5(apple = 3 + app = 2).
Constraints
1 <= key.length, prefix.length <= 50keyandprefixconsist of only lowercase English letters1 <= val <= 1000- At most
50calls will be made toinsertandsum
Approach
Trie pattern
1. Build a Trie with Prefix Sums
- Create a TrieNode class with
children(map of child nodes) andval(cumulative sum of all keys passing through this node) - Maintain a separate HashMap to store the current value of each key for handling overrides
2. Insert Operation
- When inserting
(key, val), computedelta = val - previousVal(previous value is0if key is new) - Traverse the trie character by character, creating nodes as needed
- Add
deltato each node'svalalong the path - Update the HashMap with the new value for the key
3. Sum Operation
- Traverse the trie following the characters of the prefix
- If any character is missing, return
0 - Otherwise, the
valat the last node of the prefix path is the answer — it already stores the cumulative sum of all keys with that prefix
4. Process All Operations
- Iterate through the operations array, dispatching each to the appropriate handler
- Collect results:
nullfor constructor and insert, the sum value for sum queries
Key Insight
- By storing prefix sums in each trie node and using a delta approach for updates, both
insertandsumrun in O(k) time wherekis the key/prefix length - The delta technique correctly handles key overrides without needing to recompute sums