Advanced · Hash map · Recency order

LRU Cache Visualizer

What is LRU Cache

Design a cache of fixed capacity. GET key returns the stored value, or -1 when the key is absent. PUT key value inserts or updates a key. When the cache is full, the least recently used key is removed before the new key is stored. Every successful get or put makes that key the most recent one.

Example. Capacity 2. Put 1 and 2, get 1, put 3. Key 2 is the least recent, so it leaves. Get 2 returns -1 and get 3 returns 3.

PUT 1 1, PUT 2 2, GET 1, PUT 3 3, GET 2, GET 3
Output: 1 -1 3

Constraints. 1 ≤ capacity ≤ 3000, 1 ≤ operations ≤ 104. This picture keeps capacity at 4 and draws 8 operations.

Approach

Hash map The map stores key to value and finds any key in constant time.
Recency order A doubly linked list, or an ordered map, keeps the most recent key at one end and the least recent key at the other. A hit or an update moves that key to the recent end. An eviction removes the other end.

Interactive solution

Cache order, most recent on the left
class LRUCache:
def get(self, key):
if key not in cache: return -1
move key to most recent
return value
def put(self, key, value):
if key in cache: update and move to most recent
else:
if full: evict least recent
insert key as most recent
Step 0/0 Answer —

The finished structure is on screen when the page opens. Next and Play start again from the first step.

Complexity

PieceCostWhy
GetO(1)The map finds the key and the order moves it to the recent end.
PutO(1)Update, insert, and eviction each touch one end of the order.

Implementation

def get(self, key):
    if key not in self.cache:
        return -1
    value = self.cache.pop(key)
    self.cache[key] = value
    return value

def put(self, key, value):
    if key in self.cache:
        self.cache.pop(key)
    elif len(self.cache) >= self.capacity:
        oldest = next(iter(self.cache))
        self.cache.pop(oldest)
    self.cache[key] = value