Solve LeetCode 146: LRU Cache in Python with a hash map plus doubly linked list approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.
This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete 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 |
What the problem is testing
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.
Algorithm
- 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.
- Maintain this invariant: List order is exact recency order and the map contains exactly the linked data nodes.
- Continue until every input item or reachable state has been resolved, then return the accumulated result.
Python solution
LeetCode provides the list, tree, or graph node definition used by the method.
from collections import Counter, defaultdict, deque, OrderedDict
import random
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)Why this is correct
The proof follows the maintained state: List order is exact recency order and the map contains exactly the linked data nodes. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.
Complexity
O(1) average time per operation and O(capacity) space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.
Edge cases
Updating an existing key also refreshes it; capacity can be one.
Tested reference code
This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 86. Partition List · Next: 104. Maximum Depth of Binary Tree