> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Map Sum Pairs Python Solution with Tests

> Tested Python solution for LeetCode 677 with 14 pytest cases. Generate a practice environment with lcpy.

LeetCode 677, [Medium](/catalog/medium). Topics: [Hash Table](/catalog/topics/hash-table), [String](/catalog/topics/string), [Design](/catalog/topics/design), [Trie](/catalog/topics/trie). [View on LeetCode](https://leetcode.com/problems/map-sum-pairs/description/).

Generate this problem as a practice environment: tested reference solution, 14 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 677   # by problem number
lcpy gen -s map_sum_pairs   # by problem name
```

## 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`.

### Examples

```
Input
["MapSum", "insert", "sum", "insert", "sum"]
[[], ["apple", 3], ["ap"], ["app", 2], ["ap"]]
Output
[null, null, 3, null, 5]
```

**Explanation**

```
MapSum mapSum = new MapSum();
mapSum.insert("apple", 3);
mapSum.sum("ap");           // return 3 (apple = 3)
mapSum.insert("app", 2);
mapSum.sum("ap");           // return 5 (apple + app = 3 + 2 = 5)
```

### 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`.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/map_sum_pairs/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/map_sum_pairs/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from __future__ import annotations


class MapSum:
    # Each node holds the sum of the values of every key passing through it.
    # Re-inserting a key applies only the value delta to the affected path.

    def __init__(self) -> None:
        self.children: dict[str, MapSum] = {}
        self.total = 0
        self.key_values: dict[str, int] = {}

    # Time: O(k) where k is the key length
    # Space: O(k)
    def insert(self, key: str, val: int) -> None:
        delta = val - self.key_values.get(key, 0)
        self.key_values[key] = val
        node: MapSum = self
        for char in key:
            node = node.children.setdefault(char, MapSum())
            node.total += delta

    # Time: O(p) where p is the prefix length
    # Space: O(1)
    def sum(self, prefix: str) -> int:
        node: MapSum | None = self
        for char in prefix:
            node = node.children.get(char)
            if node is None:
                return 0
        assert node is not None
        return node.total
```

## Complexity

| Time | Space |
| - | - |
| O(k) where k is the key length | O(k) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.