Implement an LRU cache with O(1) get and put.
Problem
Design a cache with a fixed capacity. get(key) returns the value (or -1) and marks the key as most recently used; put(key, value) inserts or updates and, when over capacity, evicts the least recently used key. Both must run in O(1).
Approach
Combine a HashMap (key → node, O(1) lookup) with a doubly linked list ordered by recency (O(1) move and removal given the node). The head side holds the most recent entry; the tail side the least recent. Sentinel head and tail nodes remove null checks.
import java.util.HashMap;
import java.util.Map;
class LRUCache {
private static final class Node {
int key, value;
Node prev, next;
Node(int key, int value) { this.key = key; this.value = value; }
}
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;
}
int get(int key) {
Node node = map.get(key);
if (node == null) return -1;
moveToFront(node);
return node.value;
}
void put(int key, int value) {
Node node = map.get(key);
if (node != null) {
node.value = value;
moveToFront(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);
addFirst(node);
}
private void moveToFront(Node n) { unlink(n); addFirst(n); }
private void unlink(Node n) {
n.prev.next = n.next;
n.next.prev = n.prev;
}
private void addFirst(Node n) {
n.next = head.next;
n.prev = head;
head.next.prev = n;
head.next = n;
}
}Complexity
O(1) time for get and put; O(capacity) space.
Follow-up questions interviewers ask
Try answering each one before you open it.
How would you make it thread-safe?
The simplest correct option is a single ReentrantLock (or synchronized) around get and put, since even get mutates the list. For high concurrency, use Caffeine, which records accesses in lock-free ring buffers and replays them on the eviction policy in batches, or stripe the cache into N independent segments by key hash (each with its own lock), accepting approximate global LRU.
How would you do it in two lines with the JDK?
Extend LinkedHashMap with accessOrder = true and override removeEldestEntry to return size() > capacity. Interviewers usually want the manual version to see that you understand the data structures, but mentioning this shows practical knowledge.