MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / LRUCache

Class LRUCache

cpp/Linked Lists/lru_cache.cpp:13–88  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

11};
12
13class LRUCache {
14public:
15 int capacity;
16 // A hash map that maps keys to nodes.
17 std::unordered_map<int, DoublyLinkedListNode*> hashmap;
18 // Initialize the head and tail dummy nodes and connect them to
19 // each other to establish a basic two-node doubly linked list.
20 DoublyLinkedListNode* head;
21 DoublyLinkedListNode* tail;
22 LRUCache(int capacity) : capacity(capacity) {
23 head = new DoublyLinkedListNode(-1, -1);
24 tail = new DoublyLinkedListNode(-1, -1);
25 head->next = tail;
26 tail->prev = head;
27 }
28 // Destructor: Cleans up dynamically allocated resources
29 // to prevent memory leaks. Implemented if time permits
30 // during an interview.
31 ~LRUCache() {
32 // Delete all nodes in the linked list.
33 DoublyLinkedListNode* current = head;
34 while (current != nullptr) {
35 DoublyLinkedListNode* nextNode = current->next;
36 delete current;
37 current = nextNode;
38 }
39 // Clear the hashmap.
40 hashmap.clear();
41 }
42
43 int get(int key) {
44 if (hashmap.find(key) == hashmap.end()) {
45 return -1;
46 }
47 // To make this key the most recently used, remove its node and
48 // re-add it to the tail of the linked list.
49 removeNode(hashmap[key]);
50 addToTail(hashmap[key]);
51 return hashmap[key]->val;
52 }
53
54 void put(int key, int val) {
55 // If a node with this key already exists, remove it from the
56 // linked list.
57 if (hashmap.find(key) != hashmap.end()) {
58 DoublyLinkedListNode* existingNode = hashmap[key];
59 removeNode(existingNode);
60 delete existingNode;
61 hashmap.erase(key);
62 }
63 DoublyLinkedListNode* node = new DoublyLinkedListNode(key, val);
64 hashmap[key] = node;
65 // Remove the least recently used node from the cache if adding
66 // this new node will result in an overflow.
67 if (hashmap.size() > capacity) {
68 DoublyLinkedListNode* lruNode = head->next;
69 hashmap.erase(lruNode->key);
70 removeNode(lruNode);

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected