Python coding

Cache that evicts the stalest key

Write a class LRUCache that stores at most capacity key-value pairs and follows the least-recently-used (LRU) policy.

  • get(key) returns the value stored for key, or -1 if the key is absent.
  • put(key, value) stores the pair, overwriting any old value. If the cache then holds more than capacity keys, it evicts the key that has gone longest without being used.

A put, and a get that finds its key, both count as a use. Both operations must be O(1) on average. Keys and values are non-negative integers and capacity >= 1.

The tests call the provided run_cache(capacity, ops): it builds the cache, applies each operation in order and returns the list of results (None for put, shown as null).

  • run_cache(2, [["put",1,10],["put",2,20],["get",1],["put",3,30],["get",2],["get",3]]) → [null,null,10,null,-1,30]
  • run_cache(2, [["put",1,1],["put",2,2],["put",1,100],["put",3,3],["get",1],["get",2]]) → [null,null,null,null,100,-1]
  • run_cache(1, [["put",5,50],["get",5],["put",6,60],["get",5],["get",6]]) → [null,50,null,-1,60]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Two needs: find a key in O(1), and know which key was used longest ago. A hash map gives the first; keeping the keys ordered by last use gives the second.

Hint 2

Pair the map with a doubly linked list: move a key to the newest end on every use and evict from the oldest end. Python's OrderedDict is exactly that pair.

Hint 3

The traps: a get must refresh the key, and a put on an existing key must refresh it without evicting anything.

Solution and why it works
pythonO(1) average per operation · O(capacity)
# --- your code ---
from collections import OrderedDict


class LRUCache:
    def __init__(self, capacity: int):
        self.capacity = capacity
        self.items = OrderedDict()       # least recently used first

    def get(self, key: int) -> int:
        if key not in self.items:
            return -1
        self.items.move_to_end(key)      # a read is a use
        return self.items[key]

    def put(self, key: int, value: int) -> None:
        self.items[key] = value
        self.items.move_to_end(key)
        if len(self.items) > self.capacity:
            self.items.popitem(last=False)   # evict the least recently used


# --- provided: do not edit ---
def run_cache(capacity: int, ops: list[list]) -> list:
    cache = LRUCache(capacity)
    return [getattr(cache, name)(*args) for name, *args in ops]

A hash map alone cannot say which key is stalest, and a list alone cannot find a key in O(1). Together they can: the map locates the entry, and a doubly linked list keeps entries in order of last use, so moving one to the newest end and evicting from the oldest end are both O(1). OrderedDict is that pair (move_to_end, popitem(last=False)). The traps: get must refresh the key, or you built FIFO; and overwriting an existing key must refresh it without evicting.