Map Sum Pairs - Complete Solution Guide
Map Sum Pairs is LeetCode problem 677, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
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. Implement the MapSum class: MapSum() Initializes the MapSum object. void insert(String key, int val) Inserts the key-val pair into the map. If the key already existed, the original key-value pair will be overridden to the new one. int sum(string prefix) Returns the sum of all the pairs' value whose key starts with the prefix .
Detailed Explanation
The problem requires designing a data structure, `MapSum`, that supports two main operations: `insert(key, val)` and `sum(prefix)`. The `insert` operation adds a key-value pair to the map, overwriting the value if the key already exists. The `sum` operation calculates the sum of all values in the map whose keys start with the given `prefix`. The constraints include the key and prefix lengths, value range, and the maximum number of calls to `insert` and `sum`.
Solution Approach
The solution uses a Trie to store the keys. Each node in the Trie represents a character in the key. Crucially, each node also stores the sum of all values associated with keys that pass through that node (i.e., have that node as a prefix). A separate hash map is maintained to keep track of the most recent value inserted for each key. This allows for calculating the 'delta' needed to update the prefix sums in the Trie when a key's value is updated.
Step-by-Step Algorithm
- Step 1: Initialize the Trie root node and the hash map.
- Step 2: In the `insert` function, calculate the difference (delta) between the new value and the old value (if any) for the given key.
- Step 3: Update the hash map with the new key-value pair.
- Step 4: Traverse the Trie, starting from the root, following the characters of the key.
- Step 5: For each node visited, update its `prefix_sum` by adding the delta. If a node doesn't exist for a character, create it.
- Step 6: In the `sum` function, traverse the Trie, starting from the root, following the characters of the prefix.
- Step 7: If a node is not found for a character in the prefix, return 0 (no keys with that prefix exist).
- Step 8: If the entire prefix is found in the Trie, return the `prefix_sum` of the last node visited.
Key Insights
- Insight 1: Using a Trie data structure to efficiently store and search prefixes.
- Insight 2: Maintaining a separate map to store key-value pairs to handle value updates correctly.
- Insight 3: Caching the prefix sum within each Trie node to optimize the `sum` operation.
Complexity Analysis
Time Complexity: O(K)
Space Complexity: O(K)
Topics
This problem involves: Hash Table, String, Design, Trie.
Companies
Asked at: Akuna Capital.