Video in progress

Strong Middle 🧠 Problem solving

Write an LRU cache where get and put are O(1).

A HashMap finds a node by key quickly, and a doubly linked list keeps the usage order: a used node moves to the front, and when space runs out the one at the end is evicted. The ready-made way in Java is LinkedHashMap with accessOrder=true and removeEldestEntry.

📖 Answer

The quick solution, which you can also use in production:

class LruCache<K, V> extends LinkedHashMap<K, V> {
    private final int capacity;

    LruCache(int capacity) {
        super(16, 0.75f, true);   // true means access order, not insertion order
        this.capacity = capacity;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > capacity;
    }
}

Interviewers often say "write it without LinkedHashMap". Then you write your own node class, head/tail sentinels and a HashMap<K, Node>:

  • get: take the node from the map, unlink it from the list and put it at the front;
  • put: if the key exists, update the value and move it to the front; if not, put a new node at the front; if the size is exceeded, remove tail.prev from both the list and the map.

Sentinel nodes eliminate the null checks: the code gets half as long and has fewer bugs.

One trap: with accessOrder=true, get also modifies the internal structure. So even read-only access from many threads is not safe. In a multi-threaded service, use Caffeine instead of your own LRU: it works without blocking and has a smarter eviction policy than LRU.