LRU cache

mediumFoundations~25 min · 8 tests

A buffer pool, a CDN edge, an embedding cache in front of a model API. Each one has a fixed amount of room, and when it fills up it throws out whatever was used longest ago.

Write a class LRUCache:

  • LRUCache(capacity) makes an empty cache that holds at most capacity keys.
  • get(key) returns the stored value, or None if the key isn’t there. A hit makes the key the most recently used.
  • put(key, value) stores the value. If the key already exists, update it and make it the most recently used. If adding a new key goes over capacity, evict the least recently used key first.
  • len(cache) returns the number of keys stored (implement __len__).
  • A capacity of 0 stores nothing.

Both get and put should be O(1).

>>> c = LRUCache(2)
>>> c.put("a", 1); c.put("b", 2)
>>> c.get("a")
1
>>> c.put("c", 3)      # evicts "b", the least recently used
>>> c.get("b") is None
True
Learn the ideaRead the lesson →
solution.pyPython 3.14 · Pyodide

Press ⌘ ↵ or Run to check the visible tests. Submit runs the hidden ones too. Everything runs in your browser.

⌘ ↵ to run