1. Hash Map with Linear Extreme Scan
Intuition
Keep an unordered_map of string to integer count. inc increments the integer; dec decrements it (and removes it if 0). getMaxKey and getMinKey iterate across all entries in the map to find the key with maximum or minimum count.
When to apply: When total unique keys are small (K <= 50) and get queries are rare.
Algorithm
- Step 1: In inc(key), map[key]++.
- Step 2: In dec(key), decrement map[key]; if count is 0, delete key.
- Step 3: In getMaxKey, scan map finding key with max count.
- Step 4: In getMinKey, scan map finding key with min count.
- Step 5: Return empty string if map is empty.
#include <iostream>#include <string>#include <unordered_map> using namespace std; class AllOne { unordered_map<string, int> counts;public: AllOne() {} void inc(string key) { counts[key]++; } void dec(string key) { counts[key]--; if (counts[key] == 0) counts.erase(key); } string getMaxKey() { if (counts.empty()) return ""; string maxKey = ""; int maxVal = -1; for (const auto& [k, v] : counts) { if (v > maxVal) { maxVal = v; maxKey = k; } } return maxKey; } string getMinKey() { if (counts.empty()) return ""; string minKey = ""; int minVal = 1e9; for (const auto& [k, v] : counts) { if (v < minVal) { minVal = v; minKey = k; } } return minKey; }}; int main() { AllOne allOne; allOne.inc("hello"); allOne.inc("hello"); cout << "Max: " << allOne.getMaxKey() << endl; // hello cout << "Min: " << allOne.getMinKey() << endl; // hello allOne.inc("leet"); cout << "Max: " << allOne.getMaxKey() << endl; // hello cout << "Min: " << allOne.getMinKey() << endl; // leet return 0;}Time & Space Complexity
- Time complexity:
O(1) inc/dec, O(K) getMaxKey/getMinKey - Space complexity:
O(K)