codekofi
← All problems

Problem 68

Medium

1 · Worked examples

0 / 4

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 4 outputs correctly.

The accepted solution

1struct Cell {
2 int key = 0;
3 int value = 0;
4 Cell* prev = nullptr;
5 Cell* next = nullptr;
6};
7
8struct Cache {
9 int cap;
10 Cell head, tail;
11 unordered_map<int, Cell*> at;
12
13 explicit Cache(int capacity) : cap(capacity) {
14 head.next = &tail;
15 tail.prev = &head;
16 }
17
18 void unlink(Cell* c) {
19 c->prev->next = c->next;
20 c->next->prev = c->prev;
21 }
22
23 void toFront(Cell* c) {
24 c->next = head.next;
25 c->prev = &head;
26 head.next->prev = c;
27 head.next = c;
28 }
29
30 int get(int key) {
31
32 auto it = at.find(key);
33
34 if (it == at.end()) {
35 return -1;
36 }
37
38 Cell* cell = it->second;
39
40 unlink(cell);
41 toFront(cell);
42
43 return cell->value;
44 }
45
46 void put(int key, int value) {
47
48 auto it = at.find(key);
49
50 if (it != at.end()) {
51
52 Cell* cell = it->second;
53 cell->value = value;
54
55 unlink(cell);
56 toFront(cell);
57 return;
58 }
59
60 if ((int)at.size() == cap) {
61
62 Cell* stale = tail.prev;
63
64 unlink(stale);
65 at.erase(stale->key);
66 delete stale;
67 }
68
69 Cell* fresh = new Cell{key, value, nullptr, nullptr};
70
71 at[key] = fresh;
72 toFront(fresh);
73 }
74};
75
76vector<string> solution(int capacity, const vector<string>& ops,
77 const vector<int>& keys,
78 const vector<int>& values) {
79
80 Cache cache(capacity);
81 vector<string> ans;
82
83 int n = ops.size();
84
85 for (int i = 0; i < n; i++) {
86
87 if (ops[i] == "put") {
88 cache.put(keys[i], values[i]);
89 ans.push_back("null");
90 } else {
91 int got = cache.get(keys[i]);
92 ans.push_back(to_string(got));
93 }
94 }
95
96 return ans;
97}

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.