LRU Cache
Build a fixed-size cache that throws out the least recently used key, with O(1) get and put.
The problem
Design a class LRUCache. LRUCache(capacity) creates an empty cache that holds at most capacity keys (capacity is at least 1). get(key) returns the value stored for key, or -1 if the key is not in the cache. put(key, value) stores the value, replacing any old value for that key. Both get and a put on a key count as using that key. If a put adds a new key and the cache now holds more than capacity keys, remove the key that was used least recently. Keys and values are integers. get and put must each run in O(1) average time.
Starter code
class LRUCache:
def __init__(self, capacity):
passPublic examples
obj = LRUCache(2) obj.put(1, 1) obj.put(2, 2) obj.get(1) obj.put(3, 3) obj.get(2) obj.put(4, 4) obj.get(1) obj.get(3) obj.get(4)gives[None, None, None, 1, None, -1, None, -1, 3, 4]obj = LRUCache(1) obj.put(2, 5) obj.put(4, 8) obj.get(2) obj.get(4)gives[None, None, None, -1, 8]obj = LRUCache(2) obj.get(0) obj.put(0, 0) obj.get(0)gives[None, -1, None, 0]
Solving it in the practice book needs an active paid plan.
Open it in the practice bookOne thought at a time.
