Designing an LRU Cache

Combine a hash map and a doubly linked list for O(1) get and put — the most-asked data-structure design question.

Intermediate 3 min readLesson 16 of 16 Interview Q&A

A cache keeps a limited number of items in fast storage. When it's full, it must evict something. LRU (Least Recently Used) evicts the item that hasn't been accessed for the longest time — betting that recently used data will be used again soon (temporal locality).

The requirement: get(key) and put(key, value) both in O(1).

Why two structures

  • A hash map gives O(1) lookup by key — but has no notion of order.
  • A doubly linked list keeps items in recency order and can move or remove any node in O(1) — if you already hold a pointer to that node.

So: the map stores key → node, and the list orders nodes from most to least recently used.

HashMapkey → nodeheadC:3A:1B:2tail
Most recently used next to head; least recently used (B) next to tail — evicted first.
OperationStepsCost
get(k)Look up node in map; move it to the front; return valueO(1)
put(k, v) existingUpdate value; move to frontO(1)
put(k, v) newCreate node at front, add to map; if over capacity remove the tail node and its map entryO(1)
class LRUCache {
    private static class Node {
        int key, val;
        Node prev, next;
        Node(int k, int v) { key = k; val = v; }
    }

    private final int capacity;
    private final Map<Integer, Node> map = new HashMap<>();
    private final Node head = new Node(0, 0), tail = new Node(0, 0);

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

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

    public void put(int key, int value) {
        Node n = map.get(key);
        if (n != null) {
            n.val = value;
            remove(n);
            addFront(n);
            return;
        }
        if (map.size() == capacity) {
            Node lru = tail.prev;
            remove(lru);
            map.remove(lru.key);       // why nodes store their key
        }
        n = new Node(key, value);
        addFront(n);
        map.put(key, n);
    }

    private void remove(Node n) {
        n.prev.next = n.next;
        n.next.prev = n.prev;
    }

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

// Production shortcut: LinkedHashMap in access order
class LRU<K, V> extends LinkedHashMap<K, V> {
    private final int cap;
    LRU(int cap) { super(16, 0.75f, true); this.cap = cap; }
    @Override protected boolean removeEldestEntry(Map.Entry<K, V> e) { return size() > cap; }
}

Other eviction policies

PolicyEvictsNotes
LRULeast recently usedGood default; fooled by one-time scans
LFULeast frequently usedKeeps popular items; O(1) with frequency buckets
FIFOOldest insertedSimple; ignores access pattern
RandomRandom entrySurprisingly decent, zero bookkeeping
TTLExpired entriesTime-based; combined with others
W-TinyLFUAdmission + LRUCaffeine (Java); near-optimal hit rates

Redis offers allkeys-lru, allkeys-lfu, volatile-ttl and others — and approximates LRU by sampling a few keys rather than maintaining a global list. Operating systems approximate LRU for page replacement with the clock algorithm (Page replacement).

Key takeaways
  • LRU = hash map (find node in O(1)) + doubly linked list (reorder/evict in O(1)).
  • Store the key in each node so you can delete the evicted node's map entry.
  • Sentinel head/tail nodes remove edge cases.
  • Know the library shortcuts: LinkedHashMap, OrderedDict, JS Map ordering.
Interview questions
QHow would you make the LRU cache thread-safe?medium

Simplest: one lock around get/put (both mutate the list, even get). For higher throughput, shard the cache into N independent LRUs by key hash, each with its own lock, or use a concurrent design like Caffeine that buffers access events and applies them in batches.

QDesign an LFU cache with O(1) operations.hard

Keep key → node and frequency → doubly linked list of nodes (each list in LRU order), plus minFreq. On access, move the node from list f to list f+1 and update minFreq if list f became empty. Evict from the tail of the minFreq list. New keys start at frequency 1 and set minFreq = 1.