Build an LRU cache
Implement get and put for a fixed-capacity LRU cache with O(1) operations.
What you’ll practice
This Level 3 exercise focuses on OrderedDict in the Collections curriculum. Solve the challenge prompt above using clear, idiomatic Python and the relevant language or standard-library tools.
Relevant Python reference: re — Regular expression operations, collections.OrderedDict.
Sample Test Cases
(lambda: [lru := LRUCache(2), lru.put('a',1), lru.put('b',2), lru.get('a'), lru.put('c',3), lru.get('b')][-1])()a is evictedFurther Reading
Reference Solution
Reveal Reference Solution
class LRUCache: def __init__(self, capacity): from collections import OrderedDict self.capacity, self.data = capacity, OrderedDict() def get(self, key): if key not in self.data: return -1 self.data.move_to_end(key) return self.data[key] def put(self, key, value): self.data[key] = value self.data.move_to_end(key) if len(self.data) > self.capacity: self.data.popitem(last=False)Pro Tips & Keyboard Shortcuts
Open VS Code Color Theme Quick Pick to select from 20 dark and light themes.
Open practice settings drawer to toggle line numbers, indenting, font size & hints.
Expand sidebar menu, focus search bar, and highlight search text instantly.
Instantly highlight and focus code editor from anywhere, restoring cursor right where you left off.
Collapse sidebar and close all popups or settings drawers for clean focus view.