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 object
  • void 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 one
  • int 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
Map Sum Pairs: Efficient Prefix Sum Data StructureInput Operationsinsert("apple", 3)insert("app", 2)sum("ap") → ?Trie Structurea:5p:5p:2l:3Query ResultPath: root → a → pSum at node: 5Covers: "app"(2) + "apple"(3)Each trie node stores sum of all values in its subtreeQuery time: O(prefix length) instead of O(number of keys)sum("ap") = 5
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
Asked in
Google 45 Amazon 35 Microsoft 25
38.0K Views
Medium Frequency
~25 min Avg. Time
950 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen