LRU Cache: OrderedDict Gives You O(1) Get and Put
In this series: Interview patterns in Python
LRU Cache asks for get and put in O(1). A dictionary is O(1) for lookup and is unordered for eviction. A list of keys is ordered and is O(n) to move a key to the front. You need both: a map from key to value, and a structure that can splice a node to the most-recent end in O(1). That structure is a doubly linked list. In Python, OrderedDict is that list plus the map, and move_to_end is the splice.
Say this out loud before you code. Interviewers who have banned OrderedDict want the nodes written out. Interviewers who have not are checking that you know why a single dict is not enough. Either way the design is the same.
This write-up is part of the curated interview-pattern set.
OrderedDict
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.items: OrderedDict[int, int] = OrderedDict()
def get(self, key: int) -> int:
if key not in self.items:
return -1
self.items.move_to_end(key)
return self.items[key]
def put(self, key: int, value: int) -> None:
if key in self.items:
self.items.move_to_end(key)
self.items[key] = value
if len(self.items) > self.capacity:
self.items.popitem(last=False)
move_to_end marks the key as most recently used. popitem(last=False) evicts the least recently used, the front of the order. Update of an existing key must also move it. Forgetting that is the bug: a hot key sits at the old position and gets evicted while a key you touched once stays.
get that misses must not insert. A get that inserts changes the cache and fails the next eviction. Capacity 1 is the edge they use: put(1, 1), put(2, 2), get(1) returns -1.
Capacity 0 is undefined in the usual LeetCode constraint (capacity >= 1). If they allow 0, every put evicts immediately and every get misses.
Explicit nodes, when OrderedDict is banned
Keep a dict of key to node and a dummy head and tail. get detaches the node and reinserts it before the tail. put of a new key, when size is at capacity, detaches the node after the head.
class _Node:
__slots__ = ("key", "val", "prev", "next")
def __init__(self, key: int, val: int):
self.key = key
self.val = val
self.prev: _Node | None = None
self.next: _Node | None = None
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.map: dict[int, _Node] = {}
self.head = _Node(0, 0)
self.tail = _Node(0, 0)
self.head.next = self.tail
self.tail.prev = self.head
def _detach(self, node: _Node) -> None:
node.prev.next = node.next # type: ignore[union-attr]
node.next.prev = node.prev # type: ignore[union-attr]
def _attach_tail(self, node: _Node) -> None:
last = self.tail.prev
last.next = node # type: ignore[union-attr]
node.prev = last
node.next = self.tail
self.tail.prev = node
def get(self, key: int) -> int:
node = self.map.get(key)
if node is None:
return -1
self._detach(node)
self._attach_tail(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._detach(node)
self._attach_tail(node)
return
if len(self.map) == self.capacity:
lru = self.head.next
self._detach(lru) # type: ignore[arg-type]
del self.map[lru.key] # type: ignore[union-attr]
node = _Node(key, value)
self.map[key] = node
self._attach_tail(node)
The operations are the ones OrderedDict already performs. Draw the two dummies so "remove from the middle" is visibly O(1): you have the node, you rewire its neighbors, you never scan.
Complexity and what not to do
Each call is O(1) average. Space is O(capacity).
Do not sort a list of timestamps on each call. That is O(n log n) and it misses the point of the question.
Do not keep a datetime on each entry and scan for min. That is O(n) evict.
Do not use a Python dict and rely on insertion order for eviction without move_to_end. Since 3.7, dict is ordered, but assigning an existing key does not move it to the end. d[k] = new updates in place. Without an explicit move, a hot key stays at its first-insert position and is evicted first. That is why OrderedDict.move_to_end exists.
Thread safety is out of scope unless they ask. The production version next to this question is a lock around get/put, or a concurrent map plus a separate policy. Do not start writing a lock on the whiteboard unless they say "multiple threads."
Keep reading
Subsets: Every Prefix Is a Valid Answer
LeetCode 78 in Python. Emit the power set by recording at every node, recurse with i + 1, and copy the shared buffer before the next pop.
Combination Sum: Reuse the Number, Keep the Index
LeetCode 39 in Python. Enumerate combinations that hit the target, reuse a candidate by staying at the same index, and skip generating permutations.
Generate Parentheses: Backtracking With Two Counts
LeetCode 22 in Python. Build only valid strings with two counters, skip the generate-and-filter trap, and name the Catalan-shaped search tree interviewers expect.
Daily Temperatures With a Monotonic Stack
LeetCode 739 in Python. The stack stores days still waiting for a warmer one, each index is pushed and popped once, and equal temperatures must not count.
Valid Parentheses: The Stack Problem Every Interview Starts With
LeetCode 20, Valid Parentheses, in Python. Why a stack is the only structure that works, the closing-bracket lookup trick, the three edge cases interviewers check, and the follow-ups that turn an Easy into a design question.
Course Schedule: Topological Sort Detects the Cycle
Given prerequisite pairs, decide if a course plan is possible. Kahn's algorithm in Python, the indegree trick, and the cycle case interviewers actually probe.
Newsletter
New posts, straight to your inbox
One email when a new post goes up. Double opt-in, unsubscribe anytime. Not a daily digest.
Comments
- No comments yet. Be the first.