SDE & MLE Prep

146. LRU Cache

Problem

Design LRUCache(capacity): get(key) returns the value or −1 if absent; put(key, value) inserts or updates a key, and if that pushes the size over capacity, it evicts the least recently used key. Both must run in O(1) average time.

Example: capacity 2: put(1,1), put(2,2), get(1) → 1, put(3,3) evicts key 2, get(2) → −1

Constraints: up to 2·10⁵ calls.

Hash map from key to node of a doubly linked list ordered by recency. get moves the node to the front; put inserts at the front and evicts the node before the tail when over capacity. Sentinels (head, tail) remove edge cases. Python's OrderedDict packages exactly this.

Complexity: O(1) per operation.

class LRUCache:
    def __init__(self, capacity: int):
        self.cap = capacity
        self.od = OrderedDict()      # hash map + doubly linked list in one

    def get(self, key: int) -> int:
        if key not in self.od:
            return -1
        self.od.move_to_end(key)     # most recent at the end
        return self.od[key]

    def put(self, key: int, value: int) -> None:
        self.od[key] = value
        self.od.move_to_end(key)
        if len(self.od) > self.cap:
            self.od.popitem(last=False)   # evict least recent