Q23: How do you design an LRU Cache with O(1) get and put operations?

Combine a HashMap<Integer, Node> with a Doubly Linked List (head and tail sentinel nodes):

  • HashMap: Provides $O(1)$ key-to-node lookups.
  • Doubly Linked List: Maintains recency ordering. On access/update, move node to head ($O(1)$). When capacity is exceeded, evict node before tail ($O(1)$).
LRU Cache Implementation
import java.util.HashMap;
import java.util.Map;

public class LRUCache {
    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);

    public LRUCache(int capacity) {
        this.capacity = capacity;
        head.next = tail; tail.prev = head;
    }
    public int get(int key) {
        if (!map.containsKey(key)) return -1;
        Node node = map.get(key);
        remove(node); addFirst(node);
        return node.val;
    }
    public void put(int key, int value) {
        if (map.containsKey(key)) remove(map.get(key));
        if (map.size() == capacity) {
            map.remove(tail.prev.key);
            remove(tail.prev);
        }
        Node node = new Node(key, value);
        addFirst(node); map.put(key, node);
    }
    private void remove(Node node) {
        node.prev.next = node.next;
        node.next.prev = node.prev;
    }
    private void addFirst(Node node) {
        node.next = head.next;
        node.prev = head;
        head.next.prev = node;
        head.next = node;
    }
}
💡 Combines HashMap index lookups with Doubly Linked List node movements for $O(1)$ access and eviction.
Key Takeaways
  • HashMap + Doubly Linked List achieves $O(1)$ operations.
  • Sentinel head and tail nodes simplify node addition/removal logic.
Knowledge Check

Why is a Doubly Linked List necessary instead of a Singly Linked List for O(1) LRU eviction?