Java Design Program · OT61
Implement an LRU Cache in Java
An LRU cache needs two things at O(1) cost: find an entry by key, and know which entry was used least recently. A hash map gives the first; a linked list in usage order gives the second.
Problem Statement
Implement a cache with a fixed capacity that supports get(key), returning the value or -1, and put(key, value).
Both get and put count as a use. When a new key is added to a full cache, the least recently used entry is removed first.
Input/Output Examples
capacity 2: put 1, put 2, get 1, put 3, get 2Output-1Explanation: key 1 was used after key 2, so key 2 is evicted.then get 3Output300Explanation: key 3 was just added.then put 4, get 1Output-1Explanation: key 1 is now the least recently used.Visual Explanation
- put 1, 2order12oldest first
- get 1order211 moves to the end
- put 3order13evict 2 from the front 2 removed
- get 3, put 4order34evict 1
- Donekeys [3, 4]
With a doubly linked list, moving a node to the end and removing the front node are both constant-time pointer changes, and the hash map finds any node directly.
Approaches
Both approaches give O(1) operations. One uses the JDK's LinkedHashMap; the other builds the structure by hand.
Approach 1: LinkedHashMap in Access Order (Recommended)
Idea: extend LinkedHashMap with accessOrder = true and override removeEldestEntry().
- Call
super(16, 0.75f, true)so every access moves the entry to the end. - Return
size() > capacityfromremoveEldestEntry(). - Use
getOrDefault(key, -1)for lookups.
Time: O(1) · Space: O(capacity).
Approach 2: HashMap and Doubly Linked List
Idea: map keys to nodes of a doubly linked list ordered by use; move a node to the tail on every use and evict from the head.
- Use sentinel head and tail nodes to avoid null checks.
get: find the node, move it to the tail and return its value.put: update and move an existing node, or evict the head's next node when full, then add the new node at the tail.
Time: O(1) · Space: O(capacity).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: LinkedHashMap in Access Order (Recommended)
The shortest correct answer in Java, and worth knowing for real code.
import java.util.LinkedHashMap;
import java.util.Map;
public class LruLinkedHashMap {
// accessOrder = true moves an entry to the end on every get/put; the eldest entry is the LRU one
static class LruCache extends LinkedHashMap<Integer, Integer> {
private final int capacity;
LruCache(int capacity) {
super(16, 0.75f, true);
this.capacity = capacity;
}
int getValue(int key) {
return getOrDefault(key, -1);
}
@Override
protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
return size() > capacity; // evict automatically after a put
}
}
public static void main(String[] args) {
LruCache cache = new LruCache(2);
cache.put(1, 100);
cache.put(2, 200);
System.out.println("get(1) = " + cache.getValue(1));
cache.put(3, 300); // key 2 is least recently used
System.out.println("get(2) = " + cache.getValue(2));
System.out.println("get(3) = " + cache.getValue(3));
cache.put(4, 400); // key 1 is now least recently used
System.out.println("get(1) = " + cache.getValue(1));
System.out.println("keys, oldest first: " + cache.keySet());
}
}
get(1) = 100 get(2) = -1 get(3) = 300 get(1) = -1 keys, oldest first: [3, 4]
Time complexity: O(1) · Space complexity: O(capacity).
Approach 2: HashMap and Doubly Linked List
This is what interviewers usually want to see written out, because it shows how the O(1) bound is achieved.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class LruManualList {
// HashMap for O(1) lookup + doubly linked list for O(1) reordering; head = oldest, tail = newest
static class LruCache {
private static 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); // sentinels avoid null checks
private final Node tail = new Node(0, 0);
LruCache(int capacity) {
this.capacity = capacity;
head.next = tail;
tail.prev = head;
}
int getValue(int key) {
Node n = map.get(key);
if (n == null) {
return -1;
}
moveToEnd(n);
return n.value;
}
void put(int key, int value) {
Node n = map.get(key);
if (n != null) {
n.value = value;
moveToEnd(n);
return;
}
if (map.size() == capacity) {
Node lru = head.next;
unlink(lru);
map.remove(lru.key);
}
n = new Node(key, value);
map.put(key, n);
addToEnd(n);
}
List<Integer> keys() {
List<Integer> keys = new ArrayList<>();
for (Node n = head.next; n != tail; n = n.next) {
keys.add(n.key);
}
return keys;
}
private void moveToEnd(Node n) {
unlink(n);
addToEnd(n);
}
private void unlink(Node n) {
n.prev.next = n.next;
n.next.prev = n.prev;
}
private void addToEnd(Node n) {
n.prev = tail.prev;
n.next = tail;
tail.prev.next = n;
tail.prev = n;
}
}
public static void main(String[] args) {
LruCache cache = new LruCache(2);
cache.put(1, 100);
cache.put(2, 200);
System.out.println("get(1) = " + cache.getValue(1));
cache.put(3, 300);
System.out.println("get(2) = " + cache.getValue(2));
System.out.println("get(3) = " + cache.getValue(3));
cache.put(4, 400);
System.out.println("get(1) = " + cache.getValue(1));
System.out.println("keys, oldest first: " + cache.keys());
}
}
get(1) = 100 get(2) = -1 get(3) = 300 get(1) = -1 keys, oldest first: [3, 4]
Time complexity: O(1) · Space complexity: O(capacity).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| LinkedHashMap in Access Order | O(1) | O(capacity) |
| HashMap and Doubly Linked List | O(1) | O(capacity) |
Every operation is a hash lookup plus a constant number of pointer changes, so get and put are O(1). Memory is proportional to the capacity.
Interview Tips and Recommended Approach
- Count reads as uses. A
getmust move the key to the most recent position. - Use sentinel nodes. They remove all the special cases for empty lists and end nodes.
- Know the
LinkedHashMapshortcut and say why the manual version is still asked. - Discuss thread safety. Neither version is thread-safe; wrap it or use a concurrent cache library.
Recommended Approach: LinkedHashMap in Access Order
Why: it is the idiomatic Java solution, a few lines long, with the same O(1) guarantees as the hand-written structure.