🧭 Do not search for the first 15 minutes. When stuck: re-read the requirements → define I/O → choose the data structure → trace a small example by hand → write code.
Implement a capacity-bounded LRU (Least Recently Used) cache.
cache = LRUCache(capacity=2)
cache.put("A", 10)
cache.put("B", 20)
cache.get("A") # 10 ← A is refreshed as recently used
cache.put("C", 30) # ← over capacity → B, the least recently used, is evicted
cache.get("B") # -1
get also refreshes recency. Merely reading a key makes it "just used".
Miss this and half the tests fail.put on an existing key overwrites the value and refreshes its recency too.get on a missing key returns -1 (not an exception).| Level | Added requirement |
|---|---|
| 1 | get and put |
| 2 | peek and delete |
| 3 | keys() — oldest first |
LRUCache(capacity: int)
get(key) -> value or -1
put(key, value) -> None
capacity is an integer of at least 1.get returns the value and refreshes that key's recency.put inserts a new key or overwrites an existing one; either way it refreshes recency.