LRU Cache
Difficulty: Medium
Design a cache that holds a fixed number of key-value pairs, with two operations:
-get(key): return the key's value, or -1 if it isn't cached. This marks the key as "recently used." -put(key, value): insert or update the key's value and mark it as "recently used." If a new key would exceed the capacity, first evict the least recently used key.
Both operations must run in constant average time, however many items are cached.
Examples
Input: capacity = 2; put(1,1); put(2,2); get(1); put(3,3); get(2); put(4,4); get(1); get(3); get(4)
Output: -, -, 1, -, -1, -, -1, 3, 4
put(3,3) evicts key 2 (2 was the least recently used at that point, since key 1 had just been touched by get(1)). put(4,4) then evicts key 1 for the same reason.
Input: capacity = 1; put(1,1); get(1); put(2,2); get(1); get(2)
Output: -, 1, -, -1, 2
With capacity 1, inserting key 2 always evicts whatever key was there before.
Constraints
1 <= capacity <= 3000
0 <= key, value <= 10^4
At most 2 * 10^5 total calls to get and put.
Approach
A simple first attempt keeps a plain list of key-value pairs. On get, scan for the key and move it to the "most recent" end. On put, scan the same way, and if the cache is full, drop the entry at the "least recent" end. It's correct, but scanning and reordering costs time proportional to the number of cached entries.
The constant-time version pairs two structures:
- A hash map from key to node, for instant lookup.
- A doubly linked list of the nodes in usage order (most recent at one end, least recent at the other).
With a direct node reference, you can unlink it and reinsert it at the "most recent" end in O(1), with no scanning. Eviction just removes the node at the least-recent end.
Solutions
Brute Force — Array of Pairs
Keep an array of {key, value} pairs, ordered from least recently used (front) to most recently used (back). get and put search the array linearly; a hit is moved to the back. When capacity is exceeded, the front pair (least recently used) is dropped.
class LRUCache {
constructor(capacity) {
this.capacity = capacity;
this.items = []; // ordered least-recently-used (front) to most-recently-used (back)
}
get(key) {
const index = this.items.findIndex((item) => item.key === key);
if (index === -1) return -1;
const [item] = this.items.splice(index, 1);
this.items.push(item); // now the most recently used
return item.value;
}
put(key, value) {
const index = this.items.findIndex((item) => item.key === key);
if (index !== -1) {
this.items.splice(index, 1);
} else if (this.items.length === this.capacity) {
this.items.shift(); // evict the least recently used
}
this.items.push({ key, value });
}
}Time: O(n) per get/put, where n is the number of entries currently cached · Space: O(capacity)
Optimal — Doubly Linked List + Hash Map
Keep a doubly linked list ordered by recency, with a dummy head (most recently used side) and a dummy tail (least recently used side), plus a hash map from key to node.
get: look the node up in the map. If found, move it right after the dummy head and return its value.
put: if the key exists, update its value and move it to the front. Otherwise, if the cache is full, remove the node before the dummy tail (the least recently used) and delete it from the map. Then add a new node at the front.
Lookup, unlink and insert-at-front are all constant time: the map gives a direct node reference, and the list never needs to scan.
class Node {
constructor(key, value) {
this.key = key;
this.value = value;
this.prev = null;
this.next = null;
}
}
class LRUCache {
constructor(capacity) {
this.capacity = capacity;
this.map = new Map(); // key -> Node
// Dummy sentinels: head.next is most recently used, tail.prev is least recently used.
this.head = new Node(0, 0);
this.tail = new Node(0, 0);
this.head.next = this.tail;
this.tail.prev = this.head;
}
_remove(node) {
node.prev.next = node.next;
node.next.prev = node.prev;
}
_insertAtFront(node) {
node.next = this.head.next;
node.prev = this.head;
this.head.next.prev = node;
this.head.next = node;
}
get(key) {
if (!this.map.has(key)) return -1;
const node = this.map.get(key);
this._remove(node);
this._insertAtFront(node);
return node.value;
}
put(key, value) {
if (this.map.has(key)) {
const node = this.map.get(key);
node.value = value;
this._remove(node);
this._insertAtFront(node);
return;
}
if (this.map.size === this.capacity) {
const leastRecentlyUsed = this.tail.prev;
this._remove(leastRecentlyUsed);
this.map.delete(leastRecentlyUsed.key);
}
const node = new Node(key, value);
this.map.set(key, node);
this._insertAtFront(node);
}
}Time: O(1) for both get and put · Space: O(capacity)