codekofi
← All problems

Problem 123

Medium

1 · Worked examples

0 / 3

Type an input and write what you think is the output . Each problem is converted to Web Assembly, so any possible input will show the corresponding output. Only correct predictions count.

solution()
returns

2 · Which problem is it?

Locked until you have predicted 3 outputs correctly.

The accepted solution

1struct Store {
2
3 map<string, vector<pair<int, string>>> history;
4
5 void put(const string& key, const string& value, int at) {
6 history[key].push_back({at, value});
7 }
8
9 string get(const string& key, int at) {
10
11 const auto& stamps = history[key];
12
13 int lo = 0;
14 int hi = (int)stamps.size() - 1;
15 string found;
16
17 while (lo <= hi) {
18
19 int mid = lo + (hi - lo) / 2;
20
21 if (stamps[mid].first <= at) {
22 found = stamps[mid].second;
23 lo = mid + 1;
24 } else {
25 hi = mid - 1;
26 }
27 }
28
29 return found;
30 }
31};
32
33vector<string> solution(const vector<string>& ops,
34 const vector<string>& keys,
35 const vector<string>& values,
36 const vector<int>& times) {
37
38 Store store;
39 vector<string> ans;
40
41 int n = ops.size();
42
43 for (int i = 0; i < n; i++) {
44
45 if (ops[i] == "set") {
46 store.put(keys[i], values[i], times[i]);
47 ans.push_back("null");
48
49 } else {
50 ans.push_back(store.get(keys[i], times[i]));
51 }
52 }
53
54 return ans;
55}

Names have been stripped. The signature is the only clue you get for free. Compiled as C++20 with the standard headers and using namespace std; already in scope.