LRU Cache: the idea to remember.
Implement a fixed positive capacity cache with get and put operations that evict the least recently used key.
The core insight
Map keys to nodes and move accessed nodes to the most recent end of a doubly linked list.
Why it works
The map provides direct lookup while list order records recency; removing its least recent real node enforces capacity.
The mistake to avoid
Both get and updating an existing key count as uses. Remove evicted nodes from the map as well as the list.
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
// Java reference adapted from neetcode-gh/leetcode (MIT).
// Map keys to nodes and move accessed nodes to the most recent end of a doubly linked list.
class LRUCache {
private Map<Integer, Node> cache;
private int capacity;
private Node left;
private Node right;
public LRUCache(int capacity) {
this.capacity = capacity;
cache = new HashMap<>();
this.left = new Node(0, 0);
this.right = new Node(0, 0);
this.left.next = this.right;
this.right.prev = this.left;
}
public int get(int key) {
if (cache.containsKey(key)) {
remove(cache.get(key));
insert(cache.get(key));
return cache.get(key).val;
} else {
return -1;
}
}
public void put(int key, int value) {
if (cache.containsKey(key)) {
remove(cache.get(key));
}
cache.put(key, new Node(key, value));
insert(cache.get(key));
if (cache.size() > capacity) {
Node lru = this.left.next;
remove(lru);
cache.remove(lru.key);
}
}
public void remove(Node node) {
Node prev = node.prev;
Node next = node.next;
prev.next = next;
next.prev = prev;
}
public void insert(Node node) {
Node prev = this.right.prev;
Node next = this.right;
prev.next = node;
next.prev = node;
node.next = next;
node.prev = prev;
}
private class Node {
private int key;
private int val;
Node next;
Node prev;
public Node(int key, int val) {
this.key = key;
this.val = val;
}
}
}Java reference adapted from neetcode-gh/leetcode · MIT license
Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.