← Gym/Simple Cache
00:00/ 20 min

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

python
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

Core rules

  • get also refreshes recency. Merely reading a key makes it "just used". Miss this and half the tests fail.
  • A put on an existing key overwrites the value and refreshes its recency too.
  • When capacity is exceeded, discard the single least recently used key.
  • A get on a missing key returns -1 (not an exception).

Level structure

LevelAdded requirement
1get and put
2peek and delete
3keys() — oldest first

Level 1 · get / put

python
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.
  • On overflow, discard the least recently used key.