Skip to content

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).

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 1collections.OrderedDict remembers insertion order and can move a key to the end with move_to_end(key) in O(1).
Hint 2popitem(last=False) removes the oldest entry.
Hint 3Keep the most recently used entries at the end.

Learn the concepts

More Python problems

All Python problems