-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmapSumPairs.py
More file actions
32 lines (25 loc) · 798 Bytes
/
mapSumPairs.py
File metadata and controls
32 lines (25 loc) · 798 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Source: https://leetcode.com/problems/map-sum-pairs/
# Author: Miao Zhang
# Date: 2021-02-28
class MapSum:
def __init__(self):
"""
Initialize your data structure here.
"""
self.vals = collections.defaultdict(int)
self.sums = collections.defaultdict(int)
def insert(self, key: str, val: int) -> None:
inc = val
if key in self.vals:
inc -= self.vals[key]
self.vals[key] = val
for i in range(1, len(key) + 1):
self.sums[key[0:i]] += inc
def sum(self, prefix: str) -> int:
return self.sums[prefix]
# Your MapSum object will be instantiated and called as such:
# obj = MapSum()
# obj.insert(key,val)
# param_2 = obj.sum(prefix)