Map Sum Pairs - Problem

Design a MapSum data structure that supports efficient key-value storage and prefix-based sum queries. This is a common system design problem that combines the functionality of a hash map with prefix matching capabilities.

Your task: Implement the MapSum class with the following operations:

  • MapSum() - Initialize an empty MapSum object
  • insert(key, val) - Insert or update a key-value pair. If the key already exists, override the old value
  • sum(prefix) - Return the sum of all values whose keys start with the given prefix

Example scenario: Imagine a word frequency counter where you can query the total frequency of all words starting with a certain prefix - like finding the sum of frequencies for all words starting with "app" (apple, application, approach, etc.).

The challenge is to balance the efficiency of both insertion and prefix sum operations.

Input & Output

example_1.py โ€” Basic Operations
$ Input: ["MapSum", "insert", "sum", "insert", "sum"] [[], ["apple", 3], ["ap"], ["app", 2], ["ap"]]
โ€บ Output: [null, null, 3, null, 5]
๐Ÿ’ก Note: Initially empty MapSum. Insert "apple" with value 3. Query sum("ap") returns 3 (only "apple" matches). Insert "app" with value 2. Query sum("ap") returns 5 ("apple" + "app" = 3 + 2 = 5).
example_2.py โ€” Key Override
$ Input: ["MapSum", "insert", "insert", "sum", "insert", "sum"] [[], ["aa", 3], ["aa", 2], ["a"], ["aaa", 4], ["aa"]]
โ€บ Output: [null, null, null, 2, null, 6]
๐Ÿ’ก Note: Insert "aa" with value 3, then override it with value 2. sum("a") returns 2. Insert "aaa" with value 4. sum("aa") returns 6 ("aa" + "aaa" = 2 + 4 = 6).
example_3.py โ€” No Matching Prefix
$ Input: ["MapSum", "insert", "insert", "sum", "sum"] [[], ["apple", 3], ["banana", 5], ["app"], ["xyz"]]
โ€บ Output: [null, null, null, 3, 0]
๐Ÿ’ก Note: Insert "apple"=3 and "banana"=5. sum("app") returns 3 (only "apple" starts with "app"). sum("xyz") returns 0 (no keys start with "xyz").

Visualization

Tap to expand
Smart Library Catalog: Trie with Prefix SumsBooks: "apple"=$3, "app"=$2, "apply"=$1$6Root Catalog'A' Section$6'P'$6'P''L'$5$1'''L'"app"=$2$3'E'"apple"=$3"apply"=$1Query: sum("ap") = $61. Start at Root Catalog ($6)2. Go to 'A' section ($6)3. Go to 'P' subsection ($6)โœ… Return $6 (all books starting with "ap")๐ŸŽฏ Key Insight: Each catalog node maintains the total value of all books in its section
Understanding the Visualization
1
Build the Catalog Tree
Create a tree structure where each path represents a book title
2
Maintain Running Totals
Each node tracks the sum of all books in its section
3
Handle Book Updates
When replacing a book, update all nodes along its path with the difference
4
Instant Prefix Queries
Follow the prefix path and return the sum at the final node
Key Takeaway
๐ŸŽฏ Key Insight: By storing prefix sums at each Trie node, we transform expensive O(n) prefix searches into lightning-fast O(m) path traversals, where m is just the prefix length!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(m) per operation

Both insert and sum operations traverse the Trie depth equal to key/prefix length

n
2n
โœ“ Linear Growth
Space Complexity
O(ALPHABET_SIZE * N * M)

Trie can have up to ALPHABET_SIZE children per node, with N keys of average length M

n
2n
โœ“ Linear Space

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
Asked in
Google 25 Amazon 18 Meta 12 Microsoft 8
42.0K Views
Medium Frequency
~25 min Avg. Time
1.6K 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