PracticeLevel 3: CollectionsEx 68. Build an LRU cache
0/150 Solved(0%)
Level 3Exercise #68

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

Example #1
Input:(lambda: [lru := LRUCache(2), lru.put('a',1), lru.put('b',2), lru.get('a'), lru.put('c',3), lru.get('b')][-1])()
Output:a is evicted

Further 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
Color Theme
Ctrl + K then T

Open VS Code Color Theme Quick Pick to select from 20 dark and light themes.

Editor SettingsCtrl + K

Open practice settings drawer to toggle line numbers, indenting, font size & hints.

Search MenuCtrl + /

Expand sidebar menu, focus search bar, and highlight search text instantly.

Focus Code Editor
Esc or Ctrl + `

Instantly highlight and focus code editor from anywhere, restoring cursor right where you left off.

Normal ViewEsc

Collapse sidebar and close all popups or settings drawers for clean focus view.

solution.py· Python 3.11 WASM