146. LRU Cache
Medium NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- Linked List
- Time
- O(1)
- Space
- O(N)
Standard Solution (C++)
SummaryDesign a fixed-capacity cache that evicts the least-recently-used entry when full, supporting O(1) get and put operations.
Approach
- Use a doubly-linked list to maintain recency order: the node nearest the tail is most-recently used, nearest the head is least-recently used.
- Use an unordered_map mapping each key to its list node for O(1) lookup.
- On every
getorput, move the accessed/inserted node to the tail (most-recent position). - On overflow, evict the node at the head (least-recent position) and erase it from the map.
#include <unordered_map>
using namespace std;
class LRUCache {
struct Node {
int key, val;
Node *prev, *next;
Node(int k, int v) : key(k), val(v), prev(nullptr), next(nullptr) {}
};
int capacity_;
unordered_map<int, Node*> map_; // key -> node
Node* head_; // dummy LRU sentinel
Node* tail_; // dummy MRU sentinel
// Detach node from its current position.
void unlink(Node* n) {
n->prev->next = n->next;
n->next->prev = n->prev;
}
// Insert node just before the tail (MRU position).
void insertMRU(Node* n) {
n->prev = tail_->prev;
n->next = tail_;
tail_->prev->next = n;
tail_->prev = n;
}
public:
LRUCache(int capacity) : capacity_(capacity) {
head_ = new Node(-1, -1);
tail_ = new Node(-1, -1);
head_->next = tail_;
tail_->prev = head_;
}
~LRUCache() {
for (Node* cur = head_; cur; ) {
Node* nxt = cur->next;
delete cur;
cur = nxt;
}
}
int get(int key) {
auto it = map_.find(key);
if (it == map_.end()) return -1;
Node* n = it->second;
unlink(n);
insertMRU(n);
return n->val;
}
void put(int key, int value) {
auto it = map_.find(key);
if (it != map_.end()) {
// Update existing entry and move to MRU.
Node* n = it->second;
n->val = value;
unlink(n);
insertMRU(n);
} else {
// Insert new entry.
Node* n = new Node(key, value);
map_[key] = n;
insertMRU(n);
// Evict LRU if over capacity.
if ((int)map_.size() > capacity_) {
Node* lru = head_->next;
unlink(lru);
map_.erase(lru->key);
delete lru;
}
}
}
};
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache* obj = new LRUCache(capacity);
* int param_1 = obj->get(key);
* obj->put(key, value);
*/ Time O(1) for both get and put Space O(n) where n is the cache capacity
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
struct Node {
int key;
int val;
Node* next;
Node* prev;
Node(int _key, int _val): key(_key), val(_val), next(nullptr), prev(nullptr){}
};
class LRUCache {
private:
unordered_map<int, Node*> umap;
Node* head;
Node* tail;
int cap;
void remove(Node *curNode){
curNode->prev->next=curNode->next;
curNode->next->prev=curNode->prev;
}
void add(Node *curNode){
Node* prev=tail->prev;
prev->next=curNode;
tail->prev=curNode;
curNode->prev=prev;
curNode->next=tail;
}
public:
LRUCache(int capacity) {
head=new Node(-1, -1);
tail=new Node(-1, -1);
head->next=tail;
tail->prev=head;
cap=capacity;
}
~LRUCache(){
Node* curNode=head;
while(curNode){
Node* next=curNode->next;
delete curNode;
curNode=next;
}
}
int get(int key) {
auto it=umap.find(key);
if(it!=umap.end()){
Node* curNode=it->second;
remove(curNode);
add(curNode);
return curNode->val;
}
return -1;
}
void put(int key, int value) {
Node* curNode;
auto it=umap.find(key);
if(it!=umap.end()){
curNode=it->second;
curNode->val=value;
remove(curNode);
}
else{
curNode=new Node(key, value);
umap[key]=curNode;
}
add(curNode);
if(umap.size()>cap){
Node* targetNode=head->next;
remove(targetNode);
umap.erase(targetNode->key);
delete targetNode;
}
}
};
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache* obj = new LRUCache(capacity);
* int param_1 = obj->get(key);
* obj->put(key,value);
*/
// Time Complexity: O(1) for get and put
// Space Complexity: O(N) for the cache, N is the capacity of the cache Time O(1) Space O(N)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground C++
Your solution. A driver couldn't be auto-generated for this signature — add a main() that calls the method and prints the result, then Run.
C++ ▶ Runnable Couldn't auto-generate a driver for this signature — edit to add one.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.