Editor

LRU Cache

Advanced · Write the code · from 50 Python Practice Problems with Instant Answer Checking (Beginner to Advanced)

From the lesson: 50 Python Practice Problems with Instant Answer Checking (Beginner to Advanced)

Fifty problems, each with a code editor and real tests. Write your solution, press Check, and see exactly which cases pass. Stuck? Hints reveal one at a time, and the solution unlocks once you have checked at least once. Your code and progress are saved in this browser.

Read the lesson

Write a class LRUCache(capacity) with get(key) (returns the value, or -1 if missing) and put(key, value). When it is full, put evicts the least recently used key. Reading a key with get counts as using it. Both operations must be O(1).

from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
pass
Solution unlocks after your first Check

What Check runs

Your code runs first, then each of these lines. The output must match exactly.

RunsExpected output
c = LRUCache(2) c.put("a", 1) c.put("b", 2) c.get("a") c.put("c", 3) print(c.get("a"), c.get("b"), c.get("c"))1 -1 3
c = LRUCache(1) c.put("x", 1) c.put("x", 2) print(c.get("x"))2

More practice problems

All Python exercises · 50 practice problems