[AlgoExpert] LRU Cache

LRU Cache

  • Time : O(1) for each operation
  • Space : O(maxSize)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <list>
using namespace std;

// Do not edit the class below except for the insertKeyValuePair,
// getValueFromKey, and getMostRecentKey methods. Feel free
// to add new properties and methods to the class.
class LRUCache {
void expire() {
while(cache.size() > maxSize) {
auto [key, value] = cache.back();
delete value;
cache.pop_back();
mp.erase(key);
}
}
void update(string key, int value) {
if(mp.count(key)) {
auto [k, v] = *mp[key];
delete v;
cache.erase(mp[key]);
}
int *p = new int(value);
cache.push_front({key, p});
mp[key] = cache.begin();
}
public:
int maxSize;
unordered_map<string, list<pair<string, int*>>::iterator> mp;
list<pair<string, int*>> cache;

LRUCache(int maxSize) { this->maxSize = maxSize > 1 ? maxSize : 1; }

void insertKeyValuePair(string key, int value) {
update(key, value);
expire();
}

int *getValueFromKey(string key) {
if(!mp.count(key)) return nullptr;
auto [k, v] = *mp[key];
update(k, *v);
return v;
}

string getMostRecentKey() {
if(cache.empty()) return "";

return cache.front().first;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/09/PS/AlgoExpert/lru-cache/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.