Ir al contenido
Ayotl

← Todos los retos

Interview challenge · medium · design, hash-map, doubly-linked-list

LRU Cache

El reto

El enunciado va en inglés, igual que en el vídeo.

Design a least-recently-used (LRU) cache with a fixed capacity. get(key) returns the value, or -1 if the key is not there, and counts as a use. put(key, value) inserts or updates a key, also as a use. When the cache is full, inserting a new key first evicts the key that was used longest ago.

Example

capacity 2
put(1, 1)
put(2, 2)
get(1)     ->  1      (now 1 is the most recent)
put(3, 3)             (full: evicts 2, the least recently used)
get(2)     ->  -1
get(3)     ->  3

Idea: keep the keys in order of use. The interview answer for O(1) get and put is a hash map plus a doubly linked list: the map finds the node, the list moves it to the front on every use, and the node at the back is the one to evict. Python's OrderedDict is exactly that pair, so the Python version only has to move_to_end on every use and popitem(last=False) when it overflows.

The C version is the small-cache variant: a fixed array of slots and a counter that stamps each slot with the time of its last use (0 means empty). The least recently used slot is the one with the smallest stamp, and empty slots are picked first because their stamp is 0. Each call scans the slots, so it is O(capacity) instead of O(1): fine for a handful of entries, and much shorter than writing the hash map and the list by hand.

La solución

# LRU Cache - ayotl.dev
from collections import OrderedDict


class LRUCache:
    def __init__(self, cap):
        self.cap = cap
        # keys in order of use, oldest first
        self.d = OrderedDict()

    def get(self, k):
        if k not in self.d:
            return -1
        self.d.move_to_end(k)  # just used
        return self.d[k]

    def put(self, k, v):
        self.d[k] = v
        self.d.move_to_end(k)
        if len(self.d) > self.cap:
            # evict the least recently used
            self.d.popitem(last=False)


c = LRUCache(2)
c.put(1, 1)
c.put(2, 2)
print(c.get(1))
c.put(3, 3)  # evicts key 2
print(c.get(2))
print(c.get(3))

$ python3 lru_cache.py

1

-1

3

El vídeo

Ver en YouTube →