DSA Tracker

Low-level design

Design an LRU cache

Design an in-memory cache with a fixed capacity that evicts the least recently used entry, with get and put in constant time.

Good first question for: SDE-1

Requirements to confirm first

  • get(key) returns the value or a miss, and counts as a use
  • put(key, value) inserts or updates; when the cache is full, the least recently used entry is removed first
  • Both operations run in O(1) on average
  • The capacity is fixed when the cache is created
  • Ask: is it used from many threads? Should entries also expire by time?

Write your own class list on paper before you open the answer key. Ten minutes of your own design is the practice; reading the key is only the check.

Show the answer key (write yours first)

Classes and what each one owns

LruCache<K, V>
The public get and put; owns the map and the list
Node<K, V>
A key, a value, and pointers to the previous and next node
Doubly linked list
Keeps the order of use: most recent at the head, eviction at the tail
HashMap<K, Node>
Finds the node for a key in constant time
EvictionPolicy
Optional interface, only if the interviewer also wants LFU or FIFO

How they connect

  • The map points at list nodes and the list gives the order; neither alone gives O(1) for both operations
  • Each node stores its key so the map entry can be removed when the tail is evicted
  • A head and a tail sentinel node remove every null check from insert and unlink

Design patterns that fit, and why

Strategy
The eviction rule behind an interface when LRU, LFU and FIFO must be interchangeable.
Decorator
Thread safety or hit counting wrapped around a plain cache, so the core stays simple.

Code sketch in Java

The core types and one real method. It is a sketch to talk through, not a full program.

class LruCache<K, V> {
  private final int capacity;
  private final Map<K, Node<K, V>> map = new HashMap<>();
  private final Node<K, V> head = new Node<>(), tail = new Node<>();   // sentinels, linked in the constructor

  V get(K key) {
    Node<K, V> node = map.get(key);
    if (node == null) return null;
    unlink(node); addFirst(node);
    return node.value;
  }

  void put(K key, V value) {
    Node<K, V> node = map.get(key);
    if (node != null) { node.value = value; unlink(node); addFirst(node); return; }
    if (map.size() == capacity) { Node<K, V> lru = tail.prev; unlink(lru); map.remove(lru.key); }
    node = new Node<>(key, value);
    map.put(key, node); addFirst(node);
  }
}

Edge cases to raise yourself

  • A capacity of zero or one
  • put on an existing key must update the value and the order without evicting anything
  • Many threads: a get also writes, because it moves a node, so a read lock is not enough
  • Null keys or values, if the language allows them

Where answers usually go wrong

  • A singly linked list or an array for the order. Removing from the middle is then O(n), and the question asked for O(1).
  • Not storing the key in the node. At eviction you hold the tail node and have no way to delete its map entry.
  • Calling the cache thread-safe because the map is a concurrent map. The map and the list must change together under one lock.
  • Reaching for the language's built-in ordered map on the first line. Mention it, then build it, because the interviewer wants to see the two structures.

Follow-up questions

  • Add a time-to-live per entry
  • Make it thread-safe, then make it scale on many cores
  • Change it to least frequently used