Algo-Sim › Low-Level Design
LFU Cache
Hard · Low-Level Design · step through it in Java, Python and C++ on your own input
Design a cache that evicts the least frequently used key, breaking ties by least recent use, with O(1) operations.
Problem
Design a cache like the LRU cache, but when it is full, evict the key with the fewest uses (each get or put of a key is one use). If several keys tie on use count, evict the least recently used of them. get returns -1 for a missing key.
Constraints
- get and put must both run in O(1) average time
- 1 ≤ capacity ≤ 10⁴
- 0 ≤ key ≤ 10⁵, 0 ≤ value ≤ 10⁹
- Up to 2 · 10⁵ calls
Edge cases to test
- Capacity 0: every put is ignored
- A tie in frequency: evict the least recent
puton an existing key bumps its frequency
Follow-up questions
- How is every operation O(1)?
- A map from frequency to an LRU list, plus the current minimum frequency, which only resets to 1 on insert.
- What is the weakness of pure LFU?
- Old popular keys never leave. Real caches age counts or use variants like LFU with decay or TinyLFU.
Solution
Java
class LFUCache {
private final int capacity;
private int minFreq = 0;
private final Map<Integer, Integer> vals = new HashMap<>();
private final Map<Integer, Integer> freq = new HashMap<>();
private final Map<Integer, LinkedHashSet<Integer>> buckets = new HashMap<>();
public LFUCache(int capacity) {
this.capacity = capacity;
}
public int get(int key) {
if (!vals.containsKey(key)) return -1;
touch(key);
return vals.get(key);
}
public void put(int key, int value) {
if (capacity == 0) return;
if (vals.containsKey(key)) {
vals.put(key, value);
touch(key);
return;
}
if (vals.size() == capacity) {
int victim = buckets.get(minFreq).iterator().next();
buckets.get(minFreq).remove(victim);
vals.remove(victim);
freq.remove(victim);
}
vals.put(key, value);
freq.put(key, 1);
buckets.computeIfAbsent(1, f -> new LinkedHashSet<>()).add(key);
minFreq = 1;
}
private void touch(int key) {
int f = freq.get(key);
buckets.get(f).remove(key);
if (f == minFreq && buckets.get(f).isEmpty()) minFreq++;
freq.put(key, f + 1);
buckets.computeIfAbsent(f + 1, x -> new LinkedHashSet<>()).add(key);
}
}Python
from collections import defaultdict
class LFUCache:
def __init__(self, capacity):
self.min_freq = 0
self.vals = {}
self.freq = {}
# freq -> keys in insertion order (a dict used as an ordered set)
self.buckets = defaultdict(dict)
self.capacity = capacity
def get(self, key):
if key not in self.vals:
return -1
self._touch(key)
return self.vals[key]
def put(self, key, value):
if self.capacity == 0:
return
if key in self.vals:
self.vals[key] = value
self._touch(key)
return
if len(self.vals) == self.capacity:
victim = next(iter(self.buckets[self.min_freq]))
del self.buckets[self.min_freq][victim]
del self.vals[victim]
del self.freq[victim]
self.vals[key] = value
self.freq[key] = 1
self.buckets[1][key] = None
self.min_freq = 1
def _touch(self, key):
f = self.freq[key]
del self.buckets[f][key]
if f == self.min_freq and not self.buckets[f]:
self.min_freq += 1
self.freq[key] = f + 1
self.buckets[f + 1][key] = NoneC++
#include <bits/stdc++.h>
using namespace std;
class LFUCache {
public:
int capacity;
int minFreq = 0;
unordered_map<int, int> vals = {};
unordered_map<int, int> freq = {};
unordered_map<int, list<int>> buckets = {};
unordered_map<int, list<int>::iterator> position;
LFUCache(int capacity) {
this->capacity = capacity;
}
int get(int key) {
if (!vals.count(key))
return -1;
touch(key);
return vals[key];
}
void put(int key, int value) {
if (capacity == 0)
return;
if (vals.count(key)) {
vals[key] = value;
touch(key);
return;
}
if (int(vals.size()) == capacity) {
int victim = buckets[minFreq].front();
buckets[minFreq].pop_front();
position.erase(victim);
vals.erase(victim);
freq.erase(victim);
}
vals[key] = value;
freq[key] = 1;
buckets[1].push_back(key);
position[key] = prev(buckets[1].end());
minFreq = 1;
}
void touch(int key) {
int f = freq[key];
buckets[f].erase(position[key]);
if (f == minFreq && buckets[f].empty())
minFreq++;
freq[key] = f + 1;
buckets[f + 1].push_back(key);
position[key] = prev(buckets[f + 1].end());
}
};
More Low-Level Design problems
- LRU Cache (Medium)
- Min Stack (Medium)
- Insert Delete GetRandom O(1) (Medium)
- Design Circular Queue (Medium)
- Flatten Nested List Iterator (Medium)
- Rate Limiter: Token Bucket (Medium)
- Rate Limiter: Sliding Window Log (Medium)
- Logger Rate Limiter (Easy)
- Design Hit Counter (Medium)
- Design Parking System (Easy)
- Design Tic-Tac-Toe (Medium)
- Design Twitter (Medium)
- Design Snake Game (Medium)
- Vending Machine (State pattern) (Medium)
- Elevator System (LOOK scheduling) (Medium)
- Splitwise (expense sharing) (Medium)
- Movie Ticket Booking (BookMyShow) (Medium)