MediumNo. 0677

Map Sum Pairs — LeetCode 677 Python Solution

Pattern
Trie
Topics
Design, Trie, Hash Table, String
Reading time
7 min

The 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.

Example

Input
["MapSum", "insert", "sum", "insert", "sum"]
Output
[null, null, 3, null, 5]
Explanation
MapSum mapSum = new MapSum();

Python solution

PythonSolution
class Trie:
    def __init__(self):
        self.children: List[Trie | None] = [None] * 26
        self.val: int = 0

    def insert(self, w: str, x: int):
        node = self
        for c in w:
            idx = ord(c) - ord('a')
            if node.children[idx] is None:
                node.children[idx] = Trie()
            node = node.children[idx]
            node.val += x

    def search(self, w: str) -> int:
        node = self
        for c in w:
            idx = ord(c) - ord('a')
            if node.children[idx] is None:
                return 0
            node = node.children[idx]
        return node.val


class MapSum:
    def __init__(self):
        self.d = defaultdict(int)
        self.tree = Trie()

    def insert(self, key: str, val: int) -> None:
        x = val - self.d[key]
        self.d[key] = val
        self.tree.insert(key, x)

    def sum(self, prefix: str) -> int:
        return self.tree.search(prefix)


# Your MapSum object will be instantiated and called as such:
# obj = MapSum()
# obj.insert(key,val)
# param_2 = obj.sum(prefix)

Complexity

Time
O(n)
Space · auxiliary
O(n × m × C)where n and m are the number of keys and the maximum length of the keys, respectively; and C is the size of the character set, which is 26 in this problem

Pattern: Trie

Store a set of words by their shared prefixes so lookups cost the length of the word. LeetCode 677. Map Sum Pairs is filed here because LeetCode tags it Trie, which is the vocabulary this hub collects.

The trie guide has the Python template for the pattern and the 49 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0676Implement Magic DictionaryMedium
0208Implement Trie (Prefix Tree)Medium
0745Prefix and Suffix SearchHard
2227Encrypt and Decrypt StringsHard
0139Word BreakMedium
0140Word Break IIHard

Frequently asked questions

How hard is LeetCode 677. Map Sum Pairs?

LeetCode 677. Map Sum Pairs is rated Medium on LeetCode.

What is the time complexity of LeetCode 677. Map Sum Pairs?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 677. Map Sum Pairs?

The Python solution on this page uses O(n × m × C), where n and m are the number of keys and the maximum length of the keys, respectively; and C is the size of the character set, which is 26 in this problem auxiliary space.

What topics does LeetCode 677. Map Sum Pairs cover?

LeetCode 677. Map Sum Pairs is tagged Design, Trie, Hash Table and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.