"""Least-recently-used (LRU) cache.

Idea
----
A fixed-size cache that, when full, evicts the entry that was used longest
ago. You need O(1) lookup (a hash map) *and* O(1) "move to most recent" and
"remove oldest" (a doubly linked list). ``collections.OrderedDict`` is
exactly a hash map threaded with a doubly linked list, so ``move_to_end`` and
``popitem(last=False)`` give both for free.

Complexity
----------
get / put: O(1)
Space: O(capacity)
"""

from collections import OrderedDict
from collections.abc import Hashable
from typing import Any


class LRUCache:
    def __init__(self, capacity: int) -> None:
        if capacity <= 0:
            raise ValueError("capacity must be positive")
        self.capacity = capacity
        self._data: OrderedDict[Hashable, Any] = OrderedDict()

    def get(self, key: Hashable, default: Any = None) -> Any:
        if key not in self._data:
            return default
        self._data.move_to_end(key)
        return self._data[key]

    def put(self, key: Hashable, value: Any) -> None:
        if key in self._data:
            self._data.move_to_end(key)
        self._data[key] = value
        if len(self._data) > self.capacity:
            self._data.popitem(last=False)

    def __contains__(self, key: Hashable) -> bool:
        return key in self._data

    def __len__(self) -> int:
        return len(self._data)
