Skip to content

Latest commit

 

History

History
29 lines (24 loc) · 665 Bytes

677.md

File metadata and controls

29 lines (24 loc) · 665 Bytes

677. Map Sum Pairs

Solution 1 (time O(n), space O(n^2))

class MapSum(object):

    def __init__(self):
        self.map = collections.defaultdict(int)
        self.prefix_map = collections.defaultdict(int)

    def insert(self, key, val):
        """
        :type key: str
        :type val: int
        :rtype: None
        """
        delta = val - self.map[key]
        self.map[key] = val
        for i in range(len(key)):
            self.prefix_map[key[:i + 1]] += delta

    def sum(self, prefix):
        """
        :type prefix: str
        :rtype: int
        """
        return self.prefix_map[prefix]