#677
Map Sum Pairs
MediumHash TableStringDesignTrieHash MapTrie
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Using a Trie (prefix tree) allows us to efficiently store keys and calculate the sum of values for any prefix. This structure enables us to traverse the tree based on the prefix and quickly gather the sums of all values associated with keys that share that prefix.
⚙️
Algorithm
4 steps- 1Step 1: Create a TrieNode class to represent each node in the Trie, storing children and a value.
- 2Step 2: In the MapSum class, initialize the root TrieNode and a dictionary to store key-value pairs.
- 3Step 3: For the insert operation, traverse the Trie according to the characters in the key, updating the value at the final node and storing the key in the dictionary.
- 4Step 4: For the sum operation, traverse the Trie according to the prefix and accumulate values from all descendant nodes.
solution.py29 lines
1class TrieNode:
2 def __init__(self):
3 self.children = {}
4 self.value = 0
5
6class MapSum:
7 def __init__(self):
8 self.root = TrieNode()
9 self.map = {}
10
11 def insert(self, key: str, val: int) -> None:
12 node = self.root
13 if key in self.map:
14 old_val = self.map[key]
15 val -= old_val
16 self.map[key] = val
17 for char in key:
18 if char not in node.children:
19 node.children[char] = TrieNode()
20 node = node.children[char]
21 node.value += val
22
23 def sum(self, prefix: str) -> int:
24 node = self.root
25 for char in prefix:
26 if char not in node.children:
27 return 0
28 node = node.children[char]
29 return node.valueℹ
Complexity note: The time complexity is O(n) for insertions and O(m) for sum operations, where n is the length of the key and m is the length of the prefix. The space complexity is O(n) due to the Trie structure storing each character of the keys.
- 1Using a Trie allows efficient prefix-based queries.
- 2Updating values in a Trie can be done by adjusting node values directly.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.