Map Sum Pairs - Problem
Design a map that allows you to do the following:
- Maps a string key to a given value
- Returns the sum of the values that have a key with a prefix equal to a given string
Implement the MapSum class:
MapSum()Initializes the MapSum objectvoid insert(String key, int val)Inserts the key-val pair into the map. If the key already existed, the original key-value pair will be overridden to the new oneint sum(string prefix)Returns the sum of all the pairs' value whose key starts with the prefix
Input & Output
Example 1 — Basic Operations
$
Input:
operations = ["MapSum", "insert", "sum", "insert", "sum"], values = [[], ["apple",3], ["ap"], ["app",2], ["ap"]]
›
Output:
[null, null, 3, null, 5]
💡 Note:
MapSum() creates object, insert("apple",3) adds key, sum("ap") returns 3, insert("app",2) adds another key, sum("ap") returns 3+2=5
Example 2 — Key Override
$
Input:
operations = ["MapSum", "insert", "sum", "insert", "sum"], values = [[], ["apple",3], ["app"], ["apple",2], ["app"]]
›
Output:
[null, null, 3, null, 2]
💡 Note:
After inserting apple=3, sum("app") returns 3. After updating apple=2, sum("app") returns 2 (original value overridden)
Example 3 — No Matching Prefix
$
Input:
operations = ["MapSum", "insert", "sum", "sum"], values = [[], ["apple",3], ["app"], ["xyz"]]
›
Output:
[null, null, 3, 0]
💡 Note:
sum("app") finds "apple" with prefix match, returns 3. sum("xyz") finds no keys with this prefix, returns 0
Constraints
- 1 ≤ key.length, prefix.length ≤ 50
- key and prefix consist of only lowercase English letters
- 1 ≤ val ≤ 1000
- At most 50 calls will be made to insert and sum
Visualization
Tap to expand
Understanding the Visualization
1
Input
Operations: insert keys with values, query prefix sums
2
Process
Build trie storing cumulative sums at each node
3
Output
Fast O(prefix length) sum queries
Key Takeaway
🎯 Key Insight: Trie nodes can store aggregate sums for instant prefix queries
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code