Problem
Design a cache with a fixed capacity that supports get and put in O(1) average time, and evicts the least recently used key when it is full. get returns -1 for a missing key. put updates the value if the key already exists.
Original: LeetCode 146: LRU Cache.
Examples
Example 1
`LRUCache: LRUCache(2), put(1, 1), put(2, 2), get(1), put(3, 3), get(2), put(4, 4), get(1), get(3), get(4)``[null, null, null, 1, null, -1, null, -1, 3, 4]`Constraints
1 <= capacity <= 30000 <= key <= 10^40 <= value <= 10^5- At most
2 * 10^5calls will be made togetandput.
Hints
Hint 1
Both get and put count as a use. Updating an existing key must also move it to most-recently-used, and must not grow the size.
Hint 2
O(1) LRU is a HashMap plus a doubly linked list, or LinkedHashMap in insertion/access order.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. An array or a single list is O(n) to find and to evict.
Optimal. Dummy head and tail sentinels, a map from key to node, and helpers to unlink and to insert after the head.
Alternative. Java's LinkedHashMap with accessOrder true can implement this in a few lines, but you should still be able to build the list yourself.
Complexity
- Time
- O(1)
get and put are O(1) time. Space is O(capacity).
- Space
- O(capacity)
Code
class Node:
def __init__(self, key=0, val=0) -> None:
self.key, self.val = key, val
self.prev = self.next = None
class LRUCache:
def __init__(self, capacity: int) -> None:
self.capacity = capacity
self.map: dict[int, Node] = {}
self.head, self.tail = Node(), Node()
self.head.next, self.tail.prev = self.tail, self.head
def get(self, key: int) -> int:
if key not in self.map:
return -1
node = self.map[key]
self._move_to_front(node)
return node.val
def put(self, key: int, value: int) -> None:
if key in self.map:
node = self.map[key]
node.val = value
self._move_to_front(node)
return
node = Node(key, value)
self.map[key] = node
self._insert_after_head(node)
if len(self.map) > self.capacity:
lru = self.tail.prev
self._unlink(lru)
del self.map[lru.key]
def _move_to_front(self, node: Node) -> None:
self._unlink(node)
self._insert_after_head(node)
def _unlink(self, node: Node) -> None:
node.prev.next = node.next
node.next.prev = node.prev
def _insert_after_head(self, node: Node) -> None:
node.next = self.head.next
node.prev = self.head
self.head.next.prev = node
self.head.next = node
if __name__ == "__main__":
c = LRUCache(2)
c.put(1, 1)
c.put(2, 2)
assert c.get(1) == 1
c.put(3, 3)
assert c.get(2) == -1
c.put(4, 4)
assert c.get(1) == -1 and c.get(3) == 3 and c.get(4) == 4
print("ok")import java.util.HashMap;
import java.util.Map;
public class LruCache {
private static class Node {
int key, val;
Node prev, next;
Node(int key, int val) { this.key = key; this.val = val; }
}
private final int capacity;
private final Map<Integer, Node> map = new HashMap<>();
private final Node head = new Node(0, 0);
private final Node tail = new Node(0, 0);
LruCache(int capacity) {
this.capacity = capacity;
head.next = tail;
tail.prev = head;
}
int get(int key) {
var node = map.get(key);
if (node == null) return -1;
moveToFront(node);
return node.val;
}
void put(int key, int value) {
var node = map.get(key);
if (node != null) {
node.val = value;
moveToFront(node);
return;
}
node = new Node(key, value);
map.put(key, node);
insertAfterHead(node);
if (map.size() > capacity) {
var lru = tail.prev;
unlink(lru);
map.remove(lru.key);
}
}
private void moveToFront(Node node) {
unlink(node);
insertAfterHead(node);
}
private void unlink(Node node) {
node.prev.next = node.next;
node.next.prev = node.prev;
}
private void insertAfterHead(Node node) {
node.next = head.next;
node.prev = head;
head.next.prev = node;
head.next = node;
}
public static void main(String[] args) {
var c = new LruCache(2);
c.put(1, 1);
c.put(2, 2);
if (c.get(1) != 1) throw new AssertionError();
c.put(3, 3);
if (c.get(2) != -1) throw new AssertionError();
c.put(4, 4);
if (c.get(1) != -1 || c.get(3) != 3 || c.get(4) != 4) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official sample with capacity 2: put(1,1), put(2,2), get(1) returns 1, put(3,3) evicts key 2, get(2) returns -1, put(4,4) evicts key 1, then get(1) is -1, get(3) is 3 and get(4) is 4.
- Dummy sentinels avoid null checks at the ends of the list.
Follow-ups
- LFU Cache evicts the least frequently used key, and uses LRU only as a tie-break.
- A thread-safe cache needs locking, or a concurrent structure, around the map and the list.
Interview script
"A hash map finds the node, and a doubly linked list records recency. I move a node to the front on every get and put, and I evict the tail when the map grows past capacity. Dummy head and tail nodes keep the link updates uniform."
Source: LeetCode 146: LRU Cache Source: Java SE 17 API: HashMap
Sources (2)
- LeetCode 146: LRU Cacheleetcode.com
- Java SE 17 API: HashMapdocs.oracle.com