Search⌘ K
AI Features

Solution: Map Sum Pairs

Explore how to build a Map Sum Pairs class using a Trie to handle string keys and integer values. Learn to insert and update values while maintaining cumulative prefix sums efficiently, enabling quick retrieval of the sum of all keys sharing a given prefix.

Statement

Design a data structure that supports the following operations:

  1. Insert a key-value pair:

    1. Each key is a string, and each value is an integer.

    2. If the key already exists, update its value to (overriding the previous value).

  2. Return the prefix sum:

    1. Given a string, prefix, return the total sum of all values associated with keys that start with this prefix.

To accomplish this, implement a class MapSum:

  • Constructor: Initializes the object.

  • void insert (String key, int val): Inserts the key-value pair into the data structure. If the key already exists, its value is updated to the new one.

  • int sum (String prefix): Returns the total sum of values for all keys that begin with the specified prefix.

Constraints:

  • 11 \leq key.length, prefix.length 50\leq 50

  • Both key and prefix consist of only lowercase English letters.

  • 11 \leq val 1000\leq 1000 ...