Algo-Sim › Low-Level Design

LRU Cache

Medium · Low-Level Design · step through it in Java, Python and C++ on your own input

Design a cache with O(1) get and put that evicts the least recently used key when full: a hash map plus a doubly linked list.

Problem

Design a key-value cache with a fixed capacity. get(key) returns the stored value or -1, and put(key, value) inserts or updates a key. When an insert would exceed the capacity, first evict the key that was used (read or written) least recently.

Constraints

Edge cases to test

Follow-up questions

How do you make it thread-safe?
A single lock around get and put is simplest; for more throughput, shard the cache by key hash with one lock per shard.
Why a doubly linked list?
Removing a node from the middle needs its predecessor; with prev pointers that is O(1).
What does a real cache add?
Expiry times (TTL), size-based eviction, and approximate LRU (sampling, as Redis does) to avoid list overhead.

Solution

Java

class LRUCache {
    private static class Node {
        int key, val;
        Node prev, next;
        Node(int key, int val) { this.key = key; this.val = val; }
    }
    private final Map<Integer, Node> map = new HashMap<>();
    private final Node head = new Node(0, 0), tail = new Node(0, 0);
    private final int capacity;

    public LRUCache(int capacity) {
        this.capacity = capacity;
        head.next = tail;
        tail.prev = head;
    }

    public int get(int key) {
        Node node = map.get(key);
        if (node == null) return -1;
        unlink(node);
        addFront(node);
        return node.val;
    }

    public void put(int key, int value) {
        Node node = map.get(key);
        if (node != null) {
            node.val = value;
            unlink(node);
            addFront(node);
            return;
        }
        if (map.size() == capacity) {
            Node lru = tail.prev;
            unlink(lru);
            map.remove(lru.key);
        }
        node = new Node(key, value);
        map.put(key, node);
        addFront(node);
    }

    private void unlink(Node node) {
        node.prev.next = node.next;
        node.next.prev = node.prev;
    }

    private void addFront(Node node) {
        node.next = head.next;
        node.prev = head;
        head.next.prev = node;
        head.next = node;
    }
}

Python

class Node:
    def __init__(self, key, val):
        self.key, self.val = key, val
        self.prev = self.next = None


class LRUCache:
    def __init__(self, capacity):
        self.map = {}
        self.head, self.tail = Node(0, 0), Node(0, 0)
        self.capacity = capacity
        self.head.next = self.tail
        self.tail.prev = self.head

    def get(self, key):
        node = self.map.get(key)
        if node is None:
            return -1
        self._unlink(node)
        self._add_front(node)
        return node.val

    def put(self, key, value):
        node = self.map.get(key)
        if node is not None:
            node.val = value
            self._unlink(node)
            self._add_front(node)
            return
        if len(self.map) == self.capacity:
            lru = self.tail.prev
            self._unlink(lru)
            del self.map[lru.key]
        node = Node(key, value)
        self.map[key] = node
        self._add_front(node)

    def _unlink(self, node):
        node.prev.next = node.next
        node.next.prev = node.prev

    def _add_front(self, node):
        node.next = self.head.next
        node.prev = self.head
        self.head.next.prev = node
        self.head.next = node

C++

#include <bits/stdc++.h>
using namespace std;

class LRUCache {
  public:
    class Node {
      public:
        int key, val;
        Node *prev = nullptr, *next = nullptr;
        Node(int key, int val) {
            this->key = key;
            this->val = val;
        }
    };
    unordered_map<int, Node *> map = {};
    Node *head = new Node(0, 0), *tail = new Node(0, 0);
    int capacity;

    LRUCache(int capacity) {
        this->capacity = capacity;
        head->next = tail;
        tail->prev = head;
    }

    ~LRUCache() {
        auto *node = head;
        while (node) {
            auto *next = node->next;
            delete node;
            node = next;
        }
    }

    int get(int key) {
        Node *node = map.count(key) ? map[key] : nullptr;
        if (node == nullptr)
            return -1;
        unlink(node);
        addFront(node);
        return node->val;
    }

    void put(int key, int value) {
        Node *node = map.count(key) ? map[key] : nullptr;
        if (node != nullptr) {
            node->val = value;
            unlink(node);
            addFront(node);
            return;
        }
        if (int(map.size()) == capacity) {
            Node *lru = tail->prev;
            unlink(lru);
            map.erase(lru->key);
            delete lru;
        }
        node = new Node(key, value);
        map[key] = node;
        addFront(node);
    }

    void unlink(Node *node) {
        node->prev->next = node->next;
        node->next->prev = node->prev;
    }

    void addFront(Node *node) {
        node->next = head->next;
        node->prev = head;
        head->next->prev = node;
        head->next = node;
    }
};

More Low-Level Design problems