LeetCode 460 LFU Cache (Hard, Java)


Problem Statement
Design and implement a data structure for a Least Frequently Used (LFU) cache.
Implement the LFUCache
class:
LFUCache(int capacity)
Initializes the object with the capacity of the data structure.int get(int key)
Gets the value of the key if the key exists in the cache. Otherwise, returns -1.void put(int key, int value)
Update the value of the key if present, or inserts the key if not already present. When the cache reaches its capacity, it should invalidate and remove the least frequently used key before inserting a new item. For this problem, when there is a tie (i.e., two or more keys with the same frequency), the least recently used key would be invalidated.
To determine the least frequently used key, a use counter is maintained for each key in the cache. The key with the smallest use counter is the least frequently used key.
When a key is first inserted into the cache, its use counter is set to 1
(due to the put operation). The use counter for a key in the cache is incremented either a get
or put
operation is called on it.
Example:
Input:
["LFUCache", "put", "put", "get", "put", "get", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]]
Output:
[null, null, null, 1, null, 2, 3, null, -1, 3, 4]
Explanation:
// cnt(x) = the use counter for key x
// cache=[] will show the last used order for tiebreakers (leftmost = most recent)
LFUCache lfu = new LFUCache(2);
lfu.put(1, 1); // cache=[1,_], cnt(1)=1
lfu.put(2, 2); // cache=[2,1], cnt(1)=1, cnt(2)=1
lfu.get(1); // return 1
// cache=[1,2], cnt(1)=2, cnt(2)=1
lfu.put(3, 3); // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2.
// cache=[3,1], cnt(1)=2, cnt(3)=1
lfu.get(2); // return -1 (not found)
lfu.get(3); // return 3
// cache=[3,1], cnt(1)=2, cnt(3)=2
lfu.put(4, 4); // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1.
// cache=[4,3], cnt(3)=2, cnt(4)=1
lfu.get(1); // return -1 (not found)
lfu.get(3); // return 3
// cache=[3,4], cnt(3)=3, cnt(4)=1
lfu.get(4); // return 4
// cache=[3,4], cnt(3)=3, cnt(4)=2
Constraints:
- 1 ≤ capacity ≤ 10⁴
- 0 ≤ key ≤ 10⁵
- 0 ≤ value ≤ 10⁹
- At most 2 × 10⁵ calls will be made to
get
andput
.
Algorithm Overview
The challenge is implementing two-level eviction: first by frequency (LFU), then by recency (LRU) for ties. We need efficient operations for both frequency tracking and recency ordering.
Data Structure Design
Core Components:
- HashMap for O(1) key lookup:
Map<Integer, Node> keyToNode
- HashMap for frequency groups:
Map<Integer, DoublyLinkedList> freqToList
- Minimum frequency tracking:
int minFreq
- Doubly Linked List nodes: For efficient insertion/deletion
Node Structure:
class Node {
int key, value, freq;
Node prev, next;
Node(int key, int value) {
this.key = key;
this.value = value;
this.freq = 1;
}
}
Doubly Linked List for LRU within same frequency:
class DoublyLinkedList {
Node head, tail;
DoublyLinkedList() {
head = new Node(0, 0);
tail = new Node(0, 0);
head.next = tail;
tail.prev = head;
}
void addToHead(Node node) { /* Add after head */ }
void removeNode(Node node) { /* Remove from list */ }
Node removeTail() { /* Remove before tail */ }
boolean isEmpty() { /* Check if only head and tail */ }
}
Algorithm Steps
GET Operation:
- Check if key exists in
keyToNode
- If not found, return -1
- If found:
- Remove node from current frequency list
- Increment node's frequency
- Add node to new frequency list (at head for LRU)
- Update minFreq if necessary
- Return node's value
PUT Operation:
- Check if key already exists:
- If yes: update value and treat like GET operation
- If new key:
- Check capacity: if full, evict LFU-LRU node
- Create new node with frequency 1
- Add to frequency-1 list
- Set minFreq = 1
- Add to keyToNode map
Eviction Strategy:
- Find LFU list: use
freqToList.get(minFreq)
- Remove LRU node: remove from tail of that list
- Clean up: remove from
keyToNode
and updateminFreq
if list becomes empty
Complete Implementation:
class LFUCache {
private final int capacity;
private int minFreq;
private Map<Integer, Node> keyToNode;
private Map<Integer, DoublyLinkedList> freqToList;
public LFUCache(int capacity) {
this.capacity = capacity;
this.minFreq = 1;
this.keyToNode = new HashMap<>();
this.freqToList = new HashMap<>();
}
public int get(int key) {
Node node = keyToNode.get(key);
if (node == null) return -1;
updateFreq(node);
return node.value;
}
public void put(int key, int value) {
if (capacity == 0) return;
Node node = keyToNode.get(key);
if (node != null) {
// Update existing key
node.value = value;
updateFreq(node);
return;
}
// Add new key
if (keyToNode.size() >= capacity) {
evictLFU();
}
Node newNode = new Node(key, value);
keyToNode.put(key, newNode);
freqToList.computeIfAbsent(1, k -> new DoublyLinkedList()).addToHead(newNode);
minFreq = 1;
}
private void updateFreq(Node node) {
int oldFreq = node.freq;
int newFreq = oldFreq + 1;
// Remove from old frequency list
freqToList.get(oldFreq).removeNode(node);
if (freqToList.get(oldFreq).isEmpty() && oldFreq == minFreq) {
minFreq++;
}
// Add to new frequency list
node.freq = newFreq;
freqToList.computeIfAbsent(newFreq, k -> new DoublyLinkedList()).addToHead(node);
}
private void evictLFU() {
DoublyLinkedList minFreqList = freqToList.get(minFreq);
Node nodeToEvict = minFreqList.removeTail();
keyToNode.remove(nodeToEvict.key);
}
}
Key Design Decisions:
- Two-level HashMap structure allows O(1) access to both nodes and frequency groups
- Doubly linked lists within each frequency maintain LRU order efficiently
- minFreq tracking avoids scanning all frequencies during eviction
- Lazy cleanup of empty frequency lists keeps operations simple
Complexity Analysis
Time Complexity:
GET: O(1)
- HashMap lookup: O(1)
- Doubly linked list operations: O(1)
- Frequency update: O(1)
PUT: O(1)
- HashMap operations: O(1)
- Doubly linked list operations: O(1)
- Eviction (when needed): O(1)
Space Complexity: O(capacity)
- keyToNode HashMap: O(capacity) - stores at most
capacity
nodes - freqToList HashMap: O(capacity) - at most
capacity
different frequencies - Doubly linked lists: O(capacity) - total nodes across all lists
- Additional variables: O(1)
Key Insights:
- Combining HashMap + Doubly Linked List pattern appears in both LRU and LFU caches
- Frequency grouping is crucial for efficient LFU operations
- minFreq tracking optimization prevents O(capacity) scans during eviction
- Two-level eviction policy (frequency first, then recency) requires careful state management
- The data structure demonstrates how complex caching policies can still achieve O(1) operations with proper design
Subscribe to my newsletter
Read articles from Anni Huang directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Anni Huang
Anni Huang
I am Anni HUANG, a software engineer with 3 years of experience in IDE development and Chatbot.