Say the class before you write it
In a design-a-class question, how you get to the code counts as much as the code. Before you type, say the operations and their costs, the state, the invariants and the edge cases. Here they are for an LRU cache with a fixed capacity.
get and put must both be O(1) on average, so nothing may search
All three must cost O(1):
| Operation | What it does |
|---|---|
get(key, default=None) | returns the value, and key becomes the most recent. A miss returns default and changes nothing |
put(key, value) | inserts or updates, and key becomes the most recent. A new key in a full cache first evicts the least recent |
len(cache) | how many entries are stored |
O(1) means the cost doesn't grow with n, the number of entries. That rules out anything that searches. It's O(1) on average, because get and put each start with a dict lookup.
The class must answer two questions fast. Where is this key? A dict answers that. Which key was used longest ago? That needs an order, and most of this lesson is about keeping that order cheap.
The editor holds CountingCache, a dict with two counters, hits and misses. The share of hits is how you judge a real cache. Write its get, so a miss counts and returns default and stores nothing.