1. Global List with Linear Scan
Intuition
Append all records (key, value, timestamp) to a central array.
When get(key, timestamp) is requested, scan the list (or iterate backwards) to find the entry matching key with the greatest timestamp <= requested timestamp.
Because the list contains up to N entries, each get operation requires O(N) time.
When to apply: Basic prototyping when the number of entries is minimal.
Algorithm
- Step 1: Store entries as objects { key, value, timestamp } in an array.
- Step 2: On set, push the new entry to the array.
- Step 3: On get, iterate through entries, tracking the best matching value whose timestamp is <= target.
- Step 4: Return the best found value, or empty string if none match.
#include <iostream>#include <string>#include <vector> struct Entry { std::string key; std::string val; int timestamp;}; class TimeMapBrute { std::vector<Entry> entries;public: TimeMapBrute() {} void set(const std::string& key, const std::string& value, int timestamp) { entries.push_back({key, value, timestamp}); } std::string get(const std::string& key, int timestamp) { std::string res = ""; int bestTime = -1; for (const auto& e : entries) { if (e.key == key && e.timestamp <= timestamp && e.timestamp > bestTime) { bestTime = e.timestamp; res = e.val; } } return res; }}; int main() { TimeMapBrute tm; tm.set("foo", "bar", 1); std::cout << tm.get("foo", 1) << std::endl; std::cout << tm.get("foo", 3) << std::endl; tm.set("foo", "bar2", 4); std::cout << tm.get("foo", 4) << std::endl; std::cout << tm.get("foo", 5) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(1) for set, O(N) for get where N is total set calls - Space complexity:
O(N) for storing entries