Sponsored
Sponsored
Using HashMap
This approach uses two hash maps. The first map stores the keys and their respective values, while the second map, usually called the prefix map, is used to cache the sums of prefixes. Every time a key-value pair is inserted, we iteratively update the sums of all prefixes for that key. In this approach, every insert
operation might take time proportional to the length of the key, and the sum
operation is almost constant time thanks to the prefix sums map.
Time Complexity: O(k)
for insert, where k
is the length of the key. O(1)
for sum.
Space Complexity: O(n)
, where n
is the number of keys stored.
1#include <unordered_map>
2#include <string>
3
4class MapSum {
5 std::unordered_map<std::string, int> map;
6 std::unordered_map<std::string, int> prefix_map;
7
8public:
9 MapSum() {}
10
11 void insert(std::string key, int val) {
12 int delta = val - map[key];
13 map[key] = val;
14 for (int i = 1; i <= key.length(); ++i) {
15 std::string prefix = key.substr(0, i);
16 prefix_map[prefix] += delta;
17 }
18 }
19
20 int sum(std::string prefix) {
21 return prefix_map[prefix];
22 }
23};
This C++ code maintains two unordered maps, where one stores key-value pairs and the other maintains the prefix sums. The insert
method calculates updates for each prefix, and the sum
method retrieves the sum from the prefix map.
Using Trie
This approach involves using a Trie (Prefix Tree) for storing keys. Along with each node of the Trie, maintain a map that stores prefix sum. Every time a key is inserted, traverse each node and update the corresponding prefix sum. When retrieving a sum for a given prefix, traverse the Trie up to the end of the prefix and return the stored prefix sum.
Time Complexity: O(k)
for insert and O(p)
for sum, where k
is the length of the key and p
is the length of the prefix.
Space Complexity: O(n)
, where n
is the number of keys stored in the Trie.
1
In JavaScript, TrieNode structures are composed of Maps to facilitate character-to-child-node relationships. The MapSum class incorporates these structures for key insertion and prefix sum calculation, maintaining the overall approach consistency observed in other implementations.