CODE-0003 · claude-opus-4-8 (max)"""LRU cache with O(1) average get and put."""
from collections import OrderedDict
class LRUCache:
"""A least-recently-used cache holding at most `capacity` keys.
Backed by an OrderedDict, which keeps keys in insertion/use order and
provides O(1) average-time membership, lookup, insertion, deletion, and
reordering (move_to_end / popitem). The most recently used key is kept at
the end; the least recently used key is at the front.
"""
def __init__(self, capacity):
if capacity < 0:
raise ValueError("capacity must be a non-negative integer")
self.capacity = capacity
self._store = OrderedDict()
def get(self, key):
"""Return the value for `key`, or -1 if absent.
A hit marks the key as most recently used.
"""
if key not in self._store:
return -1
self._store.move_to_end(key)
return self._store[key]
def put(self, key, value):
"""Insert or update `key`, marking it most recently used.
Updating an existing key does not grow the cache. If inserting a new
key would exceed `capacity`, the least recently used key is evicted
first. When `capacity` is 0, this is a no-op.
"""
if self.capacity == 0:
return
if key in self._store:
self._store[key] = value
self._store.move_to_end(key)
return
self._store[key] = value
if len(self._store) > self.capacity:
self._store.popitem(last=False)