-
Notifications
You must be signed in to change notification settings - Fork 2
feat(datastructures): map sum pairs #189
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| # Map Sum Pairs | ||
|
|
||
| Design a data structure that supports the following operations: | ||
|
|
||
| 1. Insert a key-value pair: | ||
| - Each key is a string, and each value is an integer. | ||
| - If the key already exists, update its value to (overriding the previous value). | ||
|
|
||
| 2. Return the prefix sum: | ||
| - Given a string, `prefix`, return the total sum of all values associated with keys that start with this prefix. | ||
|
|
||
| To accomplish this, implement a class MapSum: | ||
|
|
||
| - Constructor: Initializes the object. | ||
| - `void insert (String key, int val)`: Inserts the key-value pair into the data structure. If the key already exists, | ||
| its value is updated to the new one. | ||
| - `int sum (String prefix)`: Returns the total sum of values for all keys that begin with the specified prefix. | ||
|
|
||
| ## Constraints | ||
|
|
||
| - 1 ≤ `key.length`, `prefix.length` ≤ 50 | ||
| - Both `key` and `prefix` consist of only lowercase English letters. | ||
| - 1 ≤ `val` ≤ 1000 | ||
| - At most 50 calls will be made to insert and sum. | ||
|
|
||
| ## Examples | ||
|
|
||
|  | ||
|  | ||
|  | ||
|
|
||
| ## Topics | ||
|
|
||
| - Hash Table | ||
| - String | ||
| - Design | ||
| - Trie | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,129 @@ | ||
| from typing import Dict | ||
| from collections import Counter | ||
|
|
||
| from datastructures.trees.trie import TrieNode | ||
|
|
||
|
|
||
| class MapSumBruteForce(object): | ||
| """ | ||
| This solution to creating a map sum data structure that finds the sum of keys with a matching prefix uses a | ||
| Hash Table combined with Brute-Force Search and String Matching. | ||
|
|
||
| Time Complexity: Every insert operation is O(1). Every sum operation is O(N*P) where N is the number of items in the | ||
| map, and P is the length of the input prefix. | ||
|
|
||
| Space Complexity: The space used by map is linear in the size of all input key and val values combined. | ||
| """ | ||
|
|
||
| def __init__(self): | ||
| self.mapping: Dict[str, int] = {} | ||
|
|
||
| def insert(self, key: str, val: int) -> None: | ||
| """ | ||
| Inserts the key with the given value into the hash table | ||
| Args: | ||
| key (str): key to insert | ||
| val (int): value to insert | ||
| """ | ||
| self.mapping[key] = val | ||
|
|
||
| def sum(self, prefix: str) -> int: | ||
| """ | ||
| Finds the sum of all keys with the prefix `prefix`. | ||
| Args: | ||
| prefix (str): prefix to search for | ||
| Returns: | ||
| int: sum of all keys with the prefix `prefix` | ||
| """ | ||
| running_sum = 0 | ||
| for k, v in self.mapping.items(): | ||
| if k.startswith(prefix): | ||
| running_sum += v | ||
|
|
||
| return running_sum | ||
|
|
||
|
|
||
| class MapSumPrefix(object): | ||
| """ | ||
| We can remember the answer for all possible prefixes in a HashMap score. When we get a new (key, val) pair, we | ||
| update every prefix of key appropriately: each prefix will be changed by delta = val - map[key], where map is the | ||
| previously associated value of key (zero if undefined.) | ||
|
|
||
| Time Complexity: Every insert operation is O(K^2), where K is the length of the key, as K strings are made of an | ||
| average length of K. Every sum operation is O(1). | ||
|
|
||
| Space Complexity: The space used by map is linear in the size of all input key and val values combined. | ||
| """ | ||
|
|
||
| def __init__(self): | ||
| self.mapping: Dict[str, int] = {} | ||
| self.score = Counter() | ||
|
|
||
| def insert(self, key: str, val: int) -> None: | ||
| """ | ||
| Inserts the key with the given value into the hash table | ||
| Args: | ||
| key (str): key to insert | ||
| val (int): value to insert | ||
| """ | ||
| delta = val - self.mapping.get(key, 0) | ||
| self.mapping[key] = val | ||
| for i in range(len(key) + 1): | ||
| prefix = key[:i] | ||
| self.score[prefix] += delta | ||
|
|
||
| def sum(self, prefix: str) -> int: | ||
| """ | ||
| Finds the sum of all keys with the prefix `prefix`. | ||
| Args: | ||
| prefix (str): prefix to search for | ||
| Returns: | ||
| int: sum of all keys with the prefix `prefix` | ||
| """ | ||
| return self.score[prefix] | ||
|
|
||
|
|
||
| class MapSumTrie(object): | ||
| """ | ||
| Since we are dealing with prefixes, a Trie (prefix tree) is a natural data structure to approach this problem. For | ||
| every node of the trie corresponding to some prefix, we will remember the desired answer (score) and store it at | ||
| this node. As in the approach of using a prefix has map, this involves modifying each node by delta = val - map[key]. | ||
|
|
||
| Time Complexity: Every insert operation is O(K), where K is the length of the key. Every sum operation is O(K). | ||
| Space Complexity: The space used is linear in the size of the total input. | ||
| """ | ||
|
|
||
| def __init__(self): | ||
| self.mapping: Dict[str, int] = {} | ||
| self.score = Counter() | ||
| self.root = TrieNode() | ||
|
|
||
| def insert(self, key: str, val: int) -> None: | ||
| """ | ||
| Inserts the key with the given value into the hash table | ||
| Args: | ||
| key (str): key to insert | ||
| val (int): value to insert | ||
| """ | ||
| delta = val - self.mapping.get(key, 0) | ||
| self.mapping[key] = val | ||
| current = self.root | ||
| current.score += delta | ||
| for char in key: | ||
| current = current.children[char] | ||
| current.score += delta | ||
|
|
||
| def sum(self, prefix: str) -> int: | ||
| """ | ||
| Finds the sum of all keys with the prefix `prefix`. | ||
| Args: | ||
| prefix (str): prefix to search for | ||
| Returns: | ||
| int: sum of all keys with the prefix `prefix` | ||
| """ | ||
| current = self.root | ||
| for char in prefix: | ||
| if char not in current.children: | ||
| return 0 | ||
| current = current.children[char] | ||
| return current.score |
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,110 @@ | ||
| import unittest | ||
| from typing import Tuple, List | ||
| from parameterized import parameterized | ||
| from datastructures.map_sum import MapSumBruteForce, MapSumPrefix, MapSumTrie | ||
|
|
||
|
|
||
| MAP_SUM_TEST_CASES = [ | ||
| ( | ||
| [ | ||
| ("insert", ("apple", 3)), | ||
| ("sum", ("ap", 3)), | ||
| ("insert", ("apple", 2)), | ||
| ("sum", ("ap", 2)), | ||
| ], | ||
| ), | ||
| ( | ||
| [ | ||
| ("insert", ("apple", 3)), | ||
| ("sum", ("ap", 3)), | ||
| ("insert", ("ap", 2)), | ||
| ("sum", ("ap", 5)), | ||
| ], | ||
| ), | ||
| ( | ||
| [ | ||
| ("insert", ("apple", 3)), | ||
| ("insert", ("apple", 5)), | ||
| ("sum", ("ap", 5)), | ||
| ("insert", ("apricot", 2)), | ||
| ("sum", ("ap", 7)), | ||
| ], | ||
| ), | ||
| ( | ||
| [ | ||
| ("insert", ("car", 3)), | ||
| ("insert", ("cat", 2)), | ||
| ("insert", ("cart", 4)), | ||
| ("sum", ("ca", 9)), | ||
| ("sum", ("car", 7)), | ||
| ], | ||
| ), | ||
| ( | ||
| [ | ||
| ("insert", ("dog", 5)), | ||
| ("insert", ("cat", 7)), | ||
| ("sum", ("z", 0)), | ||
| ], | ||
| ), | ||
| ( | ||
| [ | ||
| ("insert", ("a", 3)), | ||
| ("insert", ("apple", 2)), | ||
| ("sum", ("a", 5)), | ||
| ("sum", ("app", 2)), | ||
| ], | ||
| ), | ||
| ] | ||
|
|
||
|
|
||
| class MapSumPairsTestCase(unittest.TestCase): | ||
| @parameterized.expand(MAP_SUM_TEST_CASES) | ||
| def test_map_sum_pairs_brute_force( | ||
| self, operations: List[Tuple[str, Tuple[str, int]]] | ||
| ): | ||
| map_sum = MapSumBruteForce() | ||
| for operation in operations: | ||
| cmd = operation[0] | ||
| params = operation[1] | ||
| if cmd == "insert": | ||
| key, value = params | ||
| map_sum.insert(key, value) | ||
|
|
||
| if cmd == "sum": | ||
| prefix, expected = params | ||
| actual = map_sum.sum(prefix) | ||
| self.assertEqual(expected, actual) | ||
|
|
||
| @parameterized.expand(MAP_SUM_TEST_CASES) | ||
| def test_map_sum_pairs_prefix(self, operations: List[Tuple[str, Tuple[str, int]]]): | ||
| map_sum = MapSumPrefix() | ||
| for operation in operations: | ||
| cmd = operation[0] | ||
| params = operation[1] | ||
| if cmd == "insert": | ||
| key, value = params | ||
| map_sum.insert(key, value) | ||
|
|
||
| if cmd == "sum": | ||
| prefix, expected = params | ||
| actual = map_sum.sum(prefix) | ||
| self.assertEqual(expected, actual) | ||
|
|
||
| @parameterized.expand(MAP_SUM_TEST_CASES) | ||
| def test_map_sum_pairs_trie(self, operations: List[Tuple[str, Tuple[str, int]]]): | ||
| map_sum = MapSumTrie() | ||
| for operation in operations: | ||
| cmd = operation[0] | ||
| params = operation[1] | ||
| if cmd == "insert": | ||
| key, value = params | ||
| map_sum.insert(key, value) | ||
|
|
||
| if cmd == "sum": | ||
| prefix, expected = params | ||
| actual = map_sum.sum(prefix) | ||
| self.assertEqual(expected, actual) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.