33. LRU Cache
Difficulty: Hard · Topic: OOP & classes
Write a class LRUCache(capacity) that keeps at most capacity entries and evicts the least recently used one when full. Every operation must be O(1).
get(key, default=None)returns the value (ordefault) and marks the key as recently used.put(key, value)inserts or updates; either way the key becomes the most recently used. Inserting into a full cache first evicts the least recently used key.len(cache)is the number of entries, andkey in cachechecks membership without changing the order.- A
capacitybelow 1 raisesValueError.
Your code runs in CPython on our servers against 7 tests, including hidden ones.
Sample test
c = LRUCache(2)
c.put('a', 1)
c.put('b', 2)
c.get('a')
c.put('c', 3)
('a' in c, 'b' in c, 'c' in c, len(c))Expected: (True, False, True, 2)
Hints
Hint 1
collections.OrderedDict remembers insertion order and can move a key to the end with move_to_end(key) in O(1).Hint 2
popitem(last=False) removes the oldest entry.Hint 3
Keep the most recently used entries at the end.Learn the concepts
- Counter, defaultdict and deque · 6 min read. Count, group and keep the last N with the collections module, and the traps in each.
- Dunder methods and abstract classes · 7 min read. Equality, ordering and hashing that agree, NotImplemented, and interfaces with abc.
More Python problems
- Bank Account with Validation · Easy
- Temperature with Properties · Easy
- Build Records from CSV Rows · Medium
- An Abstract Connector Class · Medium
- A Comparable Version Class · Medium
- A Transaction Context Manager · Hard