AlgoViz

Design an LRU cache

medium 85 min

Design an in-memory Least Recently Used cache with O(1) lookups, updates and evictions.

Watch lesson4:49

LRU cache with its own list, a lock and a time to live

Read it, run it, change a line and run it again.

Loading editor…

Runs as it is. The core knows nothing of locks and clocks: both are layers around it.

The same in Java
import java.util.*;public class LruDemo {    static final class LruCache<K, V> {        private static final class Node<K, V> {            final K key;            V value;            Node<K, V> prev, next;            Node(K key, V value) { this.key = key; this.value = value; }        }        private final int capacity;        private final Map<K, Node<K, V>> nodes = new HashMap<>();        private final Node<K, V> head = new Node<>(null, null), tail = new Node<>(null, null);        LruCache(int capacity) {            if (capacity < 1) throw new IllegalArgumentException("capacity must be at least 1");            this.capacity = capacity;            head.next = tail;            tail.prev = head;        }        synchronized Optional<V> get(K key) {            Node<K, V> node = nodes.get(key);            if (node == null) return Optional.empty();            unlink(node);            pushFront(node);            return Optional.of(node.value);        }        synchronized void put(K key, V value) {            Node<K, V> node = nodes.get(key);            if (node != null) {                node.value = value;                unlink(node);                pushFront(node);                return;            }            if (nodes.size() == capacity) {                Node<K, V> last = tail.prev;                unlink(last);                nodes.remove(last.key);            }            node = new Node<>(key, value);            nodes.put(key, node);            pushFront(node);        }        private void pushFront(Node<K, V> node) {            node.prev = head;            node.next = head.next;            head.next.prev = node;            head.next = node;        }        private void unlink(Node<K, V> node) {            node.prev.next = node.next;            node.next.prev = node.prev;        }    }    /** The short version: the list is inside LinkedHashMap. Not safe for threads. */    static final class ShortLru<K, V> extends LinkedHashMap<K, V> {        private final int capacity;        ShortLru(int capacity) {            super(16, 0.75f, true);                      // true: order by access            this.capacity = capacity;        }        @Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {            return size() > capacity;        }    }    public static void main(String[] args) {        var cache = new LruCache<String, Integer>(2);        cache.put("a", 1);        cache.put("b", 2);        cache.get("a");        cache.put("c", 3);        System.out.println(cache.get("a") + " " + cache.get("b"));   // Optional[1] Optional.empty    }}
The same in C++
#include <iostream>#include <list>#include <mutex>#include <optional>#include <stdexcept>#include <unordered_map>template <class K, class V>class LruCache {    using Item = std::pair<const K, V>;    size_t capacity_;    std::list<Item> order_;                                        // front is most recent    std::unordered_map<K, typename std::list<Item>::iterator> where_;    mutable std::mutex mutex_;public:    explicit LruCache(size_t capacity) : capacity_(capacity) {        if (capacity < 1) throw std::invalid_argument("capacity must be at least 1");    }    std::optional<V> get(const K& key) {        std::lock_guard guard(mutex_);        auto it = where_.find(key);        if (it == where_.end()) return std::nullopt;        order_.splice(order_.begin(), order_, it->second);          // links change, nothing is copied        return it->second->second;    }    void put(const K& key, V value) {        std::lock_guard guard(mutex_);        if (auto it = where_.find(key); it != where_.end()) {            it->second->second = std::move(value);            order_.splice(order_.begin(), order_, it->second);            return;        }        if (order_.size() == capacity_) {            where_.erase(order_.back().first);            order_.pop_back();        }        order_.emplace_front(key, std::move(value));        where_[key] = order_.begin();    }};int main() {    LruCache<std::string, int> cache(2);    cache.put("a", 1);    cache.put("b", 2);    cache.get("a");    cache.put("c", 3);    std::cout << cache.get("a").value_or(-1) << " " << cache.get("b").value_or(-1) << "\n";   // 1 -1}
The same in TypeScript
class Node<K, V> {  prev!: Node<K, V>;  next!: Node<K, V>;  readonly key: K;           // eviction starts at the node and must find the map entry  value: V;  constructor(key: K, value: V) {    this.key = key;    this.value = value;  }}class RecencyList<K, V> {  private readonly head = new Node<K, V>(undefined as K, undefined as V);  private readonly tail = new Node<K, V>(undefined as K, undefined as V);  constructor() {    this.head.next = this.tail;    this.tail.prev = this.head;  }  pushFront(node: Node<K, V>): void {    node.prev = this.head;    node.next = this.head.next;    this.head.next.prev = node;    this.head.next = node;  }  unlink(node: Node<K, V>): void {    node.prev.next = node.next;    node.next.prev = node.prev;  }  touch(node: Node<K, V>): void {    this.unlink(node);    this.pushFront(node);  }  last(): Node<K, V> | undefined {    return this.tail.prev === this.head ? undefined : this.tail.prev;  }  keys(): K[] {    const out: K[] = [];    for (let n = this.head.next; n !== this.tail; n = n.next) out.push(n.key);    return out;  }}class LruCache<K, V> {  private readonly nodes = new Map<K, Node<K, V>>();  private readonly order = new RecencyList<K, V>();  private readonly capacity: number;  constructor(capacity: number) {    if (capacity < 1) throw new Error("capacity must be at least 1");    this.capacity = capacity;  }  get(key: K): V | undefined {    const node = this.nodes.get(key);    if (!node) return undefined;    this.order.touch(node);    return node.value;  }  peek(key: K): V | undefined {    return this.nodes.get(key)?.value;  }  put(key: K, value: V): [K, V] | undefined {    const known = this.nodes.get(key);    if (known) {      known.value = value;      this.order.touch(known);      return undefined;    }    let evicted: [K, V] | undefined;    if (this.nodes.size === this.capacity) evicted = this.evict();    const node = new Node(key, value);    this.nodes.set(key, node);    this.order.pushFront(node);    return evicted;  }  private evict(): [K, V] {    const node = this.order.last()!;    this.order.unlink(node);    this.nodes.delete(node.key);    return [node.key, node.value];  }  remove(key: K): boolean {    const node = this.nodes.get(key);    if (!node) return false;    this.nodes.delete(key);    this.order.unlink(node);    return true;  }  get size(): number {    return this.nodes.size;  }  keys(): K[] {    return this.order.keys();  }}/** The short version: a Map keeps the order of insertion, so delete and set moves a key to the end. */class ShortLru<K, V> {  private readonly data = new Map<K, V>();  private readonly capacity: number;  constructor(capacity: number) {    this.capacity = capacity;  }  get(key: K): V | undefined {    if (!this.data.has(key)) return undefined;    const value = this.data.get(key)!;    this.data.delete(key);    this.data.set(key, value);    return value;  }  put(key: K, value: V): void {    if (this.data.has(key)) this.data.delete(key);    else if (this.data.size === this.capacity) this.data.delete(this.data.keys().next().value!);    this.data.set(key, value);  }}const cache = new LruCache<string, number>(2);cache.put("a", 1);cache.put("b", 2);cache.get("a");console.log(cache.put("c", 3), cache.keys()); // [ 'b', 2 ] [ 'c', 'a' ]const short = new ShortLru<string, number>(2);short.put("a", 1);short.put("b", 2);short.get("a");short.put("c", 3);console.log(short.get("a"), short.get("b")); // 1 undefined