Algorithm Puzzles: LRU Cache

Algorithm Puzzles everyday every week sometimes: LRU Cache

Puzzle

Puzzle from leetcode:

Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.

Implement the LRUCache class:

LRUCache(int capacity) Initialize the LRU cache with positive size capacity.
int get(int key) Return the value of the key if the key exists, otherwise return -1.
void put(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the least recently used key.
The functions get and put must each run in O(1) average time complexity.

Solution

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
class LRUCache final {
public:
LRUCache(const int capacity) : hashTable(capacity), usages(capacity), capacity(capacity) {}

int get(const int key) {
if (hashTable.contains(key)) {
lru.push(key);
usages[key]++;
return hashTable[key];
}

return -1;
}

void put(const int key, const int value) {
if (hashTable.size() == capacity && !hashTable.contains(key)) {
while (usages[lru.front()] > 1) {
usages[lru.front()]--;
lru.pop();
}
hashTable.erase(lru.front());
usages[lru.front()]--;
lru.pop();
}

lru.push(key);
usages[key]++;
hashTable[key] = value;
}

private:
std::unordered_map<int, int> hashTable;
std::unordered_map<int, int> usages;
std::queue<int> lru;
const size_t capacity;
};

T.C.(average): O(1)
S.C.: O(N)