Exercise: LRU cache
A cache keeps recent results so you don't recompute them. When it's full, an LRU (least recently used) cache throws out the item that was used longest ago. This is one of the most common interview questions, and a building block in System design answers.
Exercise: finish LRUCache.
get(key)returns the value, or-1if the key is missing. A hit counts as a use.put(key, value)inserts or updates. That also counts as a use. If the cache now holds more thancapacityitems, drop the least recently used.- Both must be O(1).
Hint: collections.OrderedDict remembers insertion order.
move_to_end(key) marks a key as newest, and popitem(last=False) removes
the oldest. A list of keys would make each call O(n), and the speed test
would catch it.
Press Check to run the tests.