LRU Cache
medium · design
Build a cache with a fixed capacity that supports two operations: get(key) returns the stored value, or -1 if the key is not present; put(key, value) stores the pair, updating the value if the key already exists. When the cache is full and a new key is added, the least recently used key (the one not read or written for the longest) is evicted. Reading or writing a key marks it as recently used. The cache is created with LRUCache(capacity).
Example: capacity 2. put(1, 1), put(2, 2), get(1) -> 1, put(3, 3) evicts key 2, get(2) -> -1, get(3) -> 3.
Starter code
class LRUCache:
"""A fixed-capacity cache that evicts the least recently used item."""
def __init__(self, capacity: int):
pass
def get(self, key: int) -> int:
pass
def put(self, key: int, value: int) -> None:
pass
Enable JavaScript to edit this code and run the hidden tests in your browser. Each test has a five-second execution limit. Your drafts and solved progress stay in this browser.
Return to the Python compiler