1. Hash Map Key Iteration
Intuition
Maintain unordered_map<string, int>. insert updates map[key] = val. sum(prefix) loops through all entries: if entry.key.startsWith(prefix), adds entry.val to sum.
When to apply: Quick brute force baseline.
Algorithm
- Step 1: Store
map[key] = val. - Step 2: On
sum(prefix): initializetotal = 0. - Step 3: For each
[k, v]in map: ifk.startsWith(prefix),total += v. - Step 4: Return
total.
#include <iostream>#include <string>#include <unordered_map>using namespace std; class MapSum { unordered_map<string, int> store;public: MapSum() {} void insert(string key, int val) { store[key] = val; } int sum(string prefix) { int total = 0; for (const auto& [k, v] : store) { if (k.rfind(prefix, 0) == 0) { total += v; } } return total; }}; int main() { MapSum mapSum; mapSum.insert("apple", 3); cout << "sum('ap'): " << mapSum.sum("ap") << endl; mapSum.insert("app", 2); cout << "sum('ap'): " << mapSum.sum("ap") << endl; return 0;}Time & Space Complexity
- Time complexity:
insert: O(1), sum: O(N * Prefix)— Must inspect all N keys in the map for each sum query. - Space complexity:
O(N * L)— Stores all N keys and values.
Why Brute Force Doesn't Scale:
With 10,000 descendant words, subtree traversal visits 100,000 nodes per sum call.
Precomputing scores along the insertion path reduces sum queries to an instant O(Prefix) read.