LeetCode 146: LRU Cache is a Medium linked list problem. This Python walkthrough develops a hash map plus doubly linked list solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Medium |
|---|---|
| Topic | Linked List |
| Reusable pattern | hash map plus doubly linked list |
| Complexity | O(1) average time per operation and O(capacity) space |
Recognizing the pattern
Linked-list solutions depend on preserving reachability while rewiring a constant number of pointers. Dummy nodes remove many head-only special cases.
For this problem specifically, map keys to nodes and maintain recency in a doubly linked list. Reads and writes move a node to the most-recent end; overflow evicts the least-recent node. The invariant worth writing beside the code is: List order is exact recency order and the map contains exactly the linked data nodes.
Step-by-step algorithm
- Identify the input state consumed by
get(key)and initialize the data required by the hash map plus doubly linked list pattern. - Map keys to nodes and maintain recency in a doubly linked list. Reads and writes move a node to the most-recent end; overflow evicts the least-recent node.
- After each update, verify the page’s central invariant: List order is exact recency order and the map contains exactly the linked data nodes.
- Finish only after the boundary behavior is covered: Updating an existing key also refreshes it; capacity can be one.
Python solution
LeetCode supplies the list, tree, or graph node class referenced by this method. The downloadable test suite includes compatible local node definitions so the implementation can also run outside the judge.
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.cache = OrderedDict()
def get(self, key):
if key not in self.cache:
return -1
self.cache.move_to_end(key)
return self.cache[key]
def put(self, key, value):
if key in self.cache:
self.cache.move_to_end(key)
self.cache[key] = value
if len(self.cache) > self.capacity:
self.cache.popitem(last=False)Reading the implementation
The main entry point is get(key). The implementation keeps little named state because each operation can be resolved directly from the current input position.
The method expresses the transformation directly without a general traversal loop. Early returns stop as soon as the answer is forced, avoiding work that cannot change the result. In concrete terms, map keys to nodes and maintain recency in a doubly linked list. Reads and writes move a node to the most-recent end; overflow evicts the least-recent node.
Correctness argument
Initialization. The data structure starts with exactly the information known before any input element is processed.
Preservation. Map keys to nodes and maintain recency in a doubly linked list. Reads and writes move a node to the most-recent end; overflow evicts the least-recent node. Each update records the current item without invalidating earlier decisions; consequently, list order is exact recency order and the map contains exactly the linked data nodes.
Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.
Complexity and trade-offs
O(1) average time per operation and O(capacity) space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
Copying values into an array makes indexing easy but abandons the intended pointer-space constraint and node identity. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
cache=LRUCache(2); cache.put(1,1); cache.put(2,2); assert cache.get(1)==1; cache.put(3,3); assert cache.get(2)==-1Common mistakes and edge cases
- Problem-specific boundary: Updating an existing key also refreshes it; capacity can be one.
- Pattern-level pitfall: Save the next node before changing a link, terminate reused tails, and check whether the original head can be removed.
- Invariant check: after every update, confirm that list order is exact recency order and the map contains exactly the linked data nodes.
Interview review checklist
- Explain why hash map plus doubly linked list matches the structure of this input.
- State the invariant in one sentence before tracing code: List order is exact recency order and the map contains exactly the linked data nodes.
- Derive O(1) average time per operation and O(capacity) space from how many times each element or state is visited.
- Test the boundary explicitly: Updating an existing key also refreshes it; capacity can be one.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 86. Partition List · Next: 104. Maximum Depth of Binary Tree