LFU Cache
Hard
Topics
Design a cache that evicts the least frequently used key when it is full.
LFUCache(capacity) creates the cache. get(key) returns the value or -1. put(key, value) inserts or updates.
Both get and put count as a use of the key. When the cache is full and a new key is inserted, evict the key with the smallest use count; if several tie, evict the least recently used among them.
Example 1
get and put count as a use, including a put that merely overwrites. A get on an absent or evicted key answers -1.Input: operations = ["LFUCache","put","put","get","put","get","get","put","get","get","get"], values = [[2],[1,1],[2,2],[1],[3,3],[2],[3],[4,4],[1],[3],[4]] Output: [null,null,null,1,null,-1,3,null,-1,3,4] Explanation: Inserting 3 evicts 2, which had been used once while 1 had been used twice. Inserting 4 then evicts 1.
Constraints
- 1 <= capacity <= 10^4
- 0 <= key, value <= 10^9
- At most 2 * 10^5 calls to get and put.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Eviction needs the smallest use count, so the frequencies have to be ordered — but scanning for the minimum on every eviction is what makes the naive version slow.
The key observation is that the minimum frequency only ever moves in two ways: it resets to 1 when a new key is inserted, and it can only increase by one when the last key at the current minimum is promoted. So it can be tracked in a single variable rather than searched for.
Ties are broken by recency, which means each frequency needs its own recency-ordered bucket rather than a plain set.
Approach
- Keep a map from key to its value and use count, and a map from use count to the keys at that count, held in insertion order so the oldest is identifiable.
- Track
minFreq, the smallest count currently present. - On a use (
get, or aputof an existing key), move the key from its bucket to the next one up. If its old bucket wasminFreqand is now empty, raiseminFreqby one. - On inserting a new key when full, drop the oldest key in the
minFreqbucket, then insert the newcomer at count 1 and setminFreq = 1.
Walkthrough
capacity 2
put(1,1) {1:v=1,f=1} minFreq=1
put(2,2) {1:f=1, 2:f=1} minFreq=1
get(1) -> 1, key 1 promoted to f=2 minFreq=1 (2 still at 1)
put(3,3) full: evict lowest count -> key 2
{1:f=2, 3:f=1} minFreq=1
get(2) -> -1 (evicted)
get(3) -> 3, key 3 promoted to f=2 minFreq=2Complexity
- Time — O(1): every operation is a fixed number of map and ordered-bucket updates; no search for the minimum.
- Space — O(capacity): one entry per stored key across the value, frequency and bucket maps.
Common Pitfalls
- Forgetting that
puton an existing key is also a use — it must promote the key, not just overwrite the value. - Setting
minFreqto 1 only on insertion is right; recomputing it by scanning the buckets reintroduces the cost the structure exists to avoid. - A tie on count must be broken by recency, so each bucket has to preserve insertion order rather than being an unordered set.
Full Solution — all languages
class LFUCache:
def __init__(self, capacity):
from collections import defaultdict, OrderedDict
self.cap = capacity
self.val = {}
self.freq = {}
self.buckets = defaultdict(OrderedDict)
self.minFreq = 0
def _touch(self, key):
f = self.freq[key]
del self.buckets[f][key]
if not self.buckets[f]:
del self.buckets[f]
if self.minFreq == f:
self.minFreq = f + 1
self.freq[key] = f + 1
self.buckets[f + 1][key] = None
def get(self, key):
if key not in self.val:
return -1
self._touch(key)
return self.val[key]
def put(self, key, value):
if self.cap <= 0:
return
if key in self.val:
self.val[key] = value
self._touch(key)
return
if len(self.val) >= self.cap:
old, _ = self.buckets[self.minFreq].popitem(last=False)
if not self.buckets[self.minFreq]:
del self.buckets[self.minFreq]
del self.val[old]
del self.freq[old]
self.val[key] = value
self.freq[key] = 1
self.buckets[1][key] = None
self.minFreq = 1import java.util.*;
class LFUCache {
private final int cap;
private int minFreq = 0;
private final Map<Integer, Integer> val = new HashMap<>();
private final Map<Integer, Integer> freq = new HashMap<>();
private final Map<Integer, LinkedHashSet<Integer>> buckets = new HashMap<>();
public LFUCache(int capacity) {
cap = capacity;
}
public int get(int key) {
if (!val.containsKey(key)) return -1;
touch(key);
return val.get(key);
}
public void put(int key, int value) {
if (cap <= 0) return;
if (val.containsKey(key)) {
val.put(key, value);
touch(key);
return;
}
if (val.size() >= cap) {
LinkedHashSet<Integer> b = buckets.get(minFreq);
int old = b.iterator().next();
b.remove(old);
if (b.isEmpty()) buckets.remove(minFreq);
val.remove(old);
freq.remove(old);
}
val.put(key, value);
freq.put(key, 1);
buckets.computeIfAbsent(1, x -> new LinkedHashSet<>()).add(key);
minFreq = 1;
}
private void touch(int key) {
int f = freq.get(key);
LinkedHashSet<Integer> b = buckets.get(f);
b.remove(key);
if (b.isEmpty()) {
buckets.remove(f);
if (minFreq == f) minFreq = f + 1;
}
freq.put(key, f + 1);
buckets.computeIfAbsent(f + 1, x -> new LinkedHashSet<>()).add(key);
}
}#include <bits/stdc++.h>
using namespace std;
class LFUCache {
public: LFUCache(int capacity) : cap(capacity), minFreq(0) {
}
int get(int key) {
if (!val.count(key)) return -1;
touch(key);
return val[key];
}
void put(int key, int value) {
if (cap <= 0) return;
if (val.count(key)) {
val[key] = value;
touch(key);
return;
}
if ((int)val.size() >= cap) {
int old = buckets[minFreq].front();
buckets[minFreq].pop_front();
if (buckets[minFreq].empty()) buckets.erase(minFreq);
val.erase(old);
freq.erase(old);
where.erase(old);
}
val[key] = value;
freq[key] = 1;
buckets[1].push_back(key);
where[key] = prev(buckets[1].end());
minFreq = 1;
}
private: int cap, minFreq;
unordered_map<int, int> val, freq;
unordered_map<int, list<int>> buckets;
unordered_map<int, list<int>::iterator> where;
void touch(int key) {
int f = freq[key];
buckets[f].erase(where[key]);
if (buckets[f].empty()) {
buckets.erase(f);
if (minFreq == f) minFreq = f + 1;
}
freq[key] = f + 1;
buckets[f + 1].push_back(key);
where[key] = prev(buckets[f + 1].end());
}
};class LFUCache {
constructor(capacity) {
this.cap = capacity;
this.val = new Map();
this.freq = new Map();
this.buckets = new Map();
// freq -> Map used as an ordered key set
this.minFreq = 0;
}
bucket(f) {
if (!this.buckets.has(f)) this.buckets.set(f, new Map());
return this.buckets.get(f);
}
touch(key) {
const f = this.freq.get(key);
const b = this.buckets.get(f);
b.delete(key);
if (b.size === 0) {
this.buckets.delete(f);
if (this.minFreq === f) this.minFreq = f + 1;
}
this.freq.set(key, f + 1);
this.bucket(f + 1).set(key, true);
}
get(key) {
if (!this.val.has(key)) return -1;
this.touch(key);
return this.val.get(key);
}
put(key, value) {
if (this.cap <= 0) return;
if (this.val.has(key)) {
this.val.set(key, value);
this.touch(key);
return;
}
if (this.val.size >= this.cap) {
const b = this.buckets.get(this.minFreq);
const oldest = b.keys().next().value;
b.delete(oldest);
if (b.size === 0) this.buckets.delete(this.minFreq);
this.val.delete(oldest);
this.freq.delete(oldest);
}
this.val.set(key, value);
this.freq.set(key, 1);
this.bucket(1).set(key, true);
this.minFreq = 1;
}
}