CODE-0003 · claude-opus-4-8 (medium)
from collections import OrderedDict


class LRUCache:
    """A least-recently-used cache with O(1) average get and put.

    Backed by an OrderedDict, which preserves insertion order and supports
    O(1) move-to-end and pop-from-either-end operations. The most recently
    used key is kept at the right end; the least recently used at the left.
    """

    def __init__(self, capacity):
        if capacity < 0:
            raise ValueError("capacity must be non-negative")
        self.capacity = capacity
        self._store = OrderedDict()

    def get(self, key):
        if key not in self._store:
            return -1
        # A successful get counts as a use: refresh recency.
        self._store.move_to_end(key)
        return self._store[key]

    def put(self, key, value):
        # capacity == 0 stores nothing.
        if self.capacity == 0:
            return
        if key in self._store:
            # Update value and refresh recency without growing the cache.
            self._store[key] = value
            self._store.move_to_end(key)
            return
        self._store[key] = value
        if len(self._store) > self.capacity:
            # Evict the least recently used key (left end).
            self._store.popitem(last=False)