|
| 1 | +''' |
| 2 | + Implement the MapSum class: |
| 3 | + - MapSum() Initializes the MapSum object. |
| 4 | + - void insert(String key, int val) Inserts the key-val |
| 5 | + pair into the map. If the key already existed, the |
| 6 | + original key-value pair will be overridden to the |
| 7 | + new one. |
| 8 | + - int sum(string prefix) Returns the sum of all the |
| 9 | + pairs' value whose key starts with the prefix. |
| 10 | +
|
| 11 | + Example: |
| 12 | + Input |
| 13 | + ["MapSum", "insert", "sum", "insert", "sum"] |
| 14 | + [[], ["apple", 3], ["ap"], ["app", 2], ["ap"]] |
| 15 | + Output |
| 16 | + [null, null, 3, null, 5] |
| 17 | + Explanation |
| 18 | + MapSum mapSum = new MapSum(); |
| 19 | + mapSum.insert("apple", 3); |
| 20 | + mapSum.sum("ap"); // return 3 |
| 21 | + // (apple = 3) |
| 22 | + mapSum.insert("app", 2); |
| 23 | + mapSum.sum("ap"); // return 5 |
| 24 | + // (apple + app = 3 + 2 = 5) |
| 25 | +
|
| 26 | + Constraints: |
| 27 | + - 1 <= key.length, prefix.length <= 50 |
| 28 | + - key and prefix consist of only lowercase English |
| 29 | + letters. |
| 30 | + - 1 <= val <= 1000 |
| 31 | + - At most 50 calls will be made to insert and sum. |
| 32 | +''' |
| 33 | +#Difficulty: Medium |
| 34 | +#34 / 34 test cases passed. |
| 35 | +#Runtime: 28 ms |
| 36 | +#Memory Usage: 14.3 MB |
| 37 | + |
| 38 | +#Runtime: 28 ms, faster than 86.01% of Python3 online submissions for Map Sum Pairs. |
| 39 | +#Memory Usage: 14.3 MB, less than 34.50% of Python3 online submissions for Map Sum Pairs. |
| 40 | + |
| 41 | +class MapSum: |
| 42 | + |
| 43 | + def __init__(self): |
| 44 | + """ |
| 45 | + Initialize your data structure here. |
| 46 | + """ |
| 47 | + self.letters = [None] * 26 |
| 48 | + self.value = 0 |
| 49 | + |
| 50 | + def insert(self, key: str, val: int) -> None: |
| 51 | + current = self |
| 52 | + i = 0 |
| 53 | + while i < len(key): |
| 54 | + index = ord(key[i]) - 97 |
| 55 | + if not current.letters[index]: |
| 56 | + current.letters[index] = MapSum() |
| 57 | + current = current.letters[index] |
| 58 | + i += 1 |
| 59 | + current.value = val |
| 60 | + |
| 61 | + def sum(self, prefix: str) -> int: |
| 62 | + current = self |
| 63 | + result = 0 |
| 64 | + queue = [] |
| 65 | + queue.extend(list(prefix)) |
| 66 | + while queue and current: |
| 67 | + current = current.letters[ord(queue.pop(0)) - 97] |
| 68 | + queue.append(current) |
| 69 | + while queue and current: |
| 70 | + current = queue.pop(0) |
| 71 | + queue.extend([letter for letter in current.letters if letter]) |
| 72 | + result += current.value |
| 73 | + return result |
| 74 | + |
| 75 | + |
| 76 | +# Your MapSum object will be instantiated and called as such: |
| 77 | +# obj = MapSum() |
| 78 | +# obj.insert(key,val) |
| 79 | +# param_2 = obj.sum(prefix) |
0 commit comments