LRU Cache
Build a fixed-size cache that throws out the least recently used key, with O(1) get and put.
The problem
Design a class LRUCache that is created with a positive capacity. get(key) returns the value stored for key, or -1 if the key is not in the cache. put(key, value) adds the key or updates its value, and if the cache now holds more than capacity keys, it removes the key that was used least recently. Both calls should take O(1) time on average.
Input LRUCache(2), put(7, 70), put(3, 30), get(7), put(5, 50), get(3), get(5)
Output [null, null, null, 70, null, -1, 50]
get(7) makes key 7 the most recent, so adding key 5 pushes out key 3.
Input LRUCache(1), put(4, 1), put(4, 9), get(4), put(6, 2), get(4)
Output [null, null, null, 9, null, -1]
Updating key 4 keeps a single entry. Adding key 6 then evicts key 4.
Key constraint: Every get and put has to run in O(1) time, so you can't scan the keys to find the oldest one.
How to spot the pattern
- You need fast lookup by key and a strict order by last use, at the same time.
- Items jump to the front when touched and fall off the back when space runs out.
- Every operation has to be O(1).
The idea
A hash map finds any key in O(1), but it has no idea which key is the oldest. A doubly linked list keeps keys in order of use and can unlink or move a node in O(1), as long as you already hold that node. So let the map store each key's node: the map jumps straight to the node, and the list keeps the order, with the most recent key at the front and the eviction candidate at the back.
Brute force: Keep a plain list of keys in order of use and scan it on every call, which costs O(capacity) per operation.
Step by step
- 1Keep a map from key to list node, and a doubly linked list with a dummy head and a dummy tail.
- 2
get: if the key is missing, return -1; otherwise move its node to the front and return its value. - 3
puton a key that exists: update the value and move its node to the front. - 4
puton a new key: create a node, add it at the front and record it in the map. - 5If the map now holds more than
capacitykeys, remove the node just before the tail and delete its key from the map.
See the pattern move
The linked lists pattern on a small example. Step through it, or press play.
Code
class Node:
def __init__(self, key: int = 0, value: int = 0):
self.key = key
self.value = value
self.prev = None
self.next = None
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.nodes = {} # key -> Node
# Dummy head and tail. The most recently used node sits right after head.
self.head = Node()
self.tail = Node()
self.head.next = self.tail
self.tail.prev = self.head
def _remove(self, node: Node) -> None:
node.prev.next = node.next
node.next.prev = node.prev
def _add_front(self, node: Node) -> None:
node.prev = self.head
node.next = self.head.next
self.head.next.prev = node
self.head.next = node
def get(self, key: int) -> int:
if key not in self.nodes:
return -1
node = self.nodes[key]
self._remove(node)
self._add_front(node)
return node.value
def put(self, key: int, value: int) -> None:
if key in self.nodes:
node = self.nodes[key]
node.value = value
self._remove(node)
self._add_front(node)
return
node = Node(key, value)
self.nodes[key] = node
self._add_front(node)
if len(self.nodes) > self.capacity:
lru = self.tail.prev # least recently used
self._remove(lru)
del self.nodes[lru.key]Complexity
Time
O(1)
Space
O(capacity)
Each call does a constant number of map lookups and pointer changes; the map and the list hold at most capacity keys.
Watch out for
- Forgetting that
getalso counts as a use, so it must move the node to the front too. - Treating
puton an existing key like a new key, which adds a duplicate node and evicts a key for no reason. - Keeping only the value in each node: when you evict the last node you need its key to delete it from the map.
Follow-up questions
Is there a shortcut in Python or JavaScript?
Python's OrderedDict (with move_to_end and popitem(last=False)) and JavaScript's Map, which remembers insertion order, can replace the hand-written list. Writing the list yourself shows why both calls are O(1).
What changes for an LFU cache, which evicts the least frequently used key?
You also track how often each key was used, usually with a map from use count to its own linked list, so eviction picks the lowest count and, among ties, the least recent key.
In Hinglish
Map se node turant milta hai, list se order pata chalta hai. Jo bhi key use ho, usse aage le aao; jagah kam pade toh sabse peeche wali key hatao.