IntermediateChallenge 22 of 34

Build an LRU cache

Implement LRUCache(capacity) with get(key) and put(key, value). get returns the value or -1 if missing, and marks the key as recently used. put inserts or updates; when the is over capacity, evict the least recently used key. Python dicts remember insertion order, which is all you need.

Exercise

Build an LRU cache

4 checks
class LRUCache:
    def __init__(self, capacity):
        self.capacity = capacity
        self.data = {}

    def get(self, key):
        ...

    def put(self, key, value):
        ...


cache = LRUCache(2)
cache.put("a", 1)
cache.put("b", 2)
print(cache.get("a"))   # 1, and "a" is now most recent
cache.put("c", 3)       # evicts "b"
print(cache.get("b"))   # -1
 
Python (loads on first run)Ctrl+Enter runs
Output
Press Run to try your code, then Check answer to grade it.