Skip to content

Practice Map Sum Pairs

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Medium#677
LeetCode Problem

Map Sum Pairs

Problem Statement

MapSum.insert(key,val) maps a string key to an integer value, replacing an earlier value for that key. sum(prefix) adds values of all stored keys beginning with prefix and returns zero when none match. Practice approach: A trie can store the sum under each prefix. Keep previous complete-key values so replacement updates every prefix by the difference, not the full new value. Both operations then take O(L) for key or prefix length L. With the small call limit, scanning a normal map is also adequate. Test replacement and one key that is a prefix of another.

Source: Map Sum Pairs on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
["MapSum","insert","insert","sum","insert","sum","sum"]
[[],["car",4],["cart",7],["car"],["car",2],["car"],["z"]]
Output
[null,null,null,11,null,9,0]
Explanation

Replacing car changes its contribution from 4 to 2 while cart remains 7.

Constraints

1 <= key.length, prefix.length <= 50
Keys and prefixes contain lowercase letters.
1 <= val <= 1000
At most 50 total calls.

Related LeetCode Problems

Practice more problems similar to Map Sum Pairs.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.