The trick here is to name the state correctly, then let the implementation follow. For 981. Time Based Key-Value Store, the solution in this repository is mainly a data structure design solution.
Guide
What?
Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: data structure design, two pointers, greedy.
The notes already sitting in the source point us in the right direction:
- Approach 1: HashMap + Binary Search
- TLE
- 44 / 45 test cases passed.
- time: O(1) for set, O(logN) for get, space: O(N)
Guide
When?
Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are set, get.
Guide
Why?
The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.
- Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
- A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Read the setup variables first.
- Follow the main loop or recursive helper next.
- Watch where invalid states get skipped.
- Check which value survives to the return statement.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(1) for set, O(logN) for get, space: O(N)
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//Approach 1: HashMap + Binary Search
02//TLE
03//44 / 45 test cases passed.
04//time: O(1) for set, O(logN) for get, space: O(N)
05class TimeMap {
06public:
07 map<string, vector<pair<int, string>>> db;
08
09 /** Initialize your data structure here. */
10 TimeMap() {
11
12 }
13
14 void set(string key, string value, int timestamp) {
15 db[key].push_back(make_pair(timestamp, value));
16 //actually the input is already sorted by timestamp, so we don't this
17 // sort(db[key].begin(), db[key].end());
18 }
19
20 string get(string key, int timestamp) {
21 // cout << "finding " << timestamp << endl;
22 if(db.find(key) == db.end()){
23 return "";
24 }else{
25 vector<pair<int, string>> values = db[key];
26 int l = 0, r = values.size()-1;
27 while(l <= r){
28 int mid = (l+r)/2;
29 // cout << l << " " << mid << " " << r << endl;
30 if(timestamp == values[mid].first){
31 return values[mid].second;
32 }else if(timestamp < values[mid].first){
33 //values[r] becomes the largest value < values[mid]
34 r = mid-1;
35 }else {
36 //when mid and r are N-1, l will become N and break the loop
37 l = mid+1;
38 }
39 }
40 // cout << "ends at " << r << endl;
41 if(r < 0) return "";
42 return values[r].second;
43 }
44 }
45};
46
47/**
48 * Your TimeMap object will be instantiated and called as such:
49 * TimeMap* obj = new TimeMap();
50 * obj->set(key,value,timestamp);
51 * string param_2 = obj->get(key,timestamp);
52 */
53
54//Approach 2: TreeMap
55//TLE
56//44 / 45 test cases passed.
57//time: O(1) for set, O(logN) for get, space: O(N)
58class TimeMap {
59public:
60 template<typename Key, typename Value>
61 using MapIterator = typename std::map<Key,Value>::const_iterator;
62
63 //https://codereview.stackexchange.com/questions/222587/java-treemap-floorkey-equivalent-for-stdmap
64 template<typename Key, typename Value>
65 Value floorValue(const std::map<Key,Value>& input, const Key& key){
66 MapIterator<Key, Value> it = input.upper_bound(key);
67 if (it != input.begin()) {
68 return (--it)->second;
69 } else {
70 //assume Value is string
71 return "";
72 }
73 }
74
75 map<string, map<int, string>> db;
76
77 /** Initialize your data structure here. */
78 TimeMap() {
79
80 }
81
82 void set(string key, string value, int timestamp) {
83 db[key][timestamp] = value;
84 }
85
86 string get(string key, int timestamp) {
87 if(db.find(key) == db.end()){
88 return "";
89 }
90 map<int, string> innermap = db[key];
91 return floorValue(innermap, timestamp);
92 }
93};
94
95/**
96 * Your TimeMap object will be instantiated and called as such:
97 * TimeMap* obj = new TimeMap();
98 * obj->set(key,value,timestamp);
99 * string param_2 = obj->get(key,timestamp);
100 */
101
102//hash map + map
103//https://leetcode.com/problems/time-based-key-value-store/discuss/226664/C%2B%2B-3-lines-hash-map-%2B-map
104//suppose there are n set and m get operations
105//time: set O(1) each, O(n) total/ get O(logn) each, O(mlogn) total
106//space: O(n)
107class TimeMap {
108public:
109 /*
110 the outer map uses unordered_map to speed up
111 if we change the outer map into map, the running time will be:
112 Runtime: 420 ms, faster than 39.75% of C++ online submissions for Time Based Key-Value Store.
113 */
114 //the inner map should be in order, so that we can use std::map::upper_bound!
115 unordered_map<string, map<int, string>> db;
116
117 /** Initialize your data structure here. */
118 TimeMap() {
119
120 }
121
122 void set(string key, string value, int timestamp) {
123 //both work
124 db[key][timestamp] = value;
125 // db[key].insert({timestamp, value});
126 }
127
128 string get(string key, int timestamp) {
129 auto it = db[key].upper_bound(timestamp);
130 if(it == db[key].begin()) return "";
131 it--; //get previous pair
132 return it->second;
133 }
134};
135
136/**
137 * Your TimeMap object will be instantiated and called as such:
138 * TimeMap* obj = new TimeMap();
139 * obj->set(key,value,timestamp);
140 * string param_2 = obj->get(key,timestamp);
141 */
142
143//hash map + vector of pair
144//https://leetcode.com/problems/time-based-key-value-store/discuss/226664/C%2B%2B-3-lines-hash-map-%2B-map
145//Runtime: 388 ms, faster than 85.11% of C++ online submissions for Time Based Key-Value Store.
146//Memory Usage: 133.1 MB, less than 100.00% of C++ online submissions for Time Based Key-Value Store.
147class TimeMap {
148public:
149 unordered_map<string, vector<pair<int, string>>> db;
150
151 /** Initialize your data structure here. */
152 TimeMap() {
153
154 }
155
156 void set(string key, string value, int timestamp) {
157 db[key].push_back({timestamp, value});
158 }
159
160 string get(string key, int timestamp) {
161 auto it = upper_bound(begin(db[key]), end(db[key]),
162 pair<int, string>(timestamp, ""),
163 [](const pair<int, string>& a, const pair<int, string>& b) {
164 return a.first < b.first;
165 });
166 return it == db[key].begin() ? "" : prev(it)->second;
167 }
168};
169
170/**
171 * Your TimeMap object will be instantiated and called as such:
172 * TimeMap* obj = new TimeMap();
173 * obj->set(key,value,timestamp);
174 * string param_2 = obj->get(key,timestamp);
175 */
Cost