460. LFU Cache
Asked at 29Amazon54Apple49Microsoft41Google37Meta15Bloomberg14IMC96Salesforce80BNY Mellon75Arista Networks60Goldman Sachs28Netskope100Coupang94Citadel74DevRev72Oracle70Walmart Labs66Wells Fargo65Nutanix60PayPal58ServiceNow55Snap55Expedia54Netflix49Rippling46Visa39Uber35TikTok35LinkedIn32
Problem
Design LFUCache(capacity) with get(key) and put(key, value) in O(1) average time. When full, put evicts the least frequently used key (counting both gets and puts), breaking ties by evicting the least recently used among them.
Example: capacity 2: put(1,1), put(2,2), get(1) → 1, put(3,3) evicts key 2 (used once), get(2) → −1
key → (value, freq), freq → OrderedDict of keys (LRU order within a frequency), plus minFreq. On access, move the key from bucket f to f+1 (bump minFreq if bucket f emptied and was the min). On insert, evict the oldest key in minFreq's bucket, then set minFreq = 1.
freq 1: [k3] minFreq = 1 -> evict k3 first
freq 2: [k1, k4] (k1 older than k4)
freq 5: [k2]
Complexity: O(1) per operation.
class LFUCache:
def __init__(self, capacity: int):
self.cap = capacity
self.kv = {} # key -> [value, freq]
self.buckets = defaultdict(OrderedDict) # freq -> keys in LRU order
self.min_f = 0
def _touch(self, key):
val, f = self.kv[key]
del self.buckets[f][key]
if not self.buckets[f]:
del self.buckets[f]
if self.min_f == f:
self.min_f += 1
self.kv[key][1] = f + 1
self.buckets[f + 1][key] = None
def get(self, key: int) -> int:
if key not in self.kv:
return -1
self._touch(key)
return self.kv[key][0]
def put(self, key: int, value: int) -> None:
if self.cap == 0:
return
if key in self.kv:
self.kv[key][0] = value
self._touch(key)
return
if len(self.kv) == self.cap:
old, _ = self.buckets[self.min_f].popitem(last=False)
del self.kv[old]
self.kv[key] = [value, 1]
self.buckets[1][key] = None
self.min_f = 1
c = LFUCache(2)
c.put(1, 1); c.put(2, 2)
assert c.get(1) == 1
c.put(3, 3) # evicts 2 (freq 1)
assert c.get(2) == -1 and c.get(3) == 3
c.put(4, 4) # 1 and 3 both freq 2 -> evict LRU among them = 1
assert c.get(1) == -1 and c.get(3) == 3 and c.get(4) == 4
class LFUCache {
private final int cap;
private int minF = 0;
private final Map<Integer, int[]> kv = new HashMap<>(); // key -> {value, freq}
private final Map<Integer, LinkedHashSet<Integer>> buckets = new HashMap<>(); // freq -> keys (LRU order)
public LFUCache(int capacity) { cap = capacity; }
private void touch(int key) {
int[] e = kv.get(key);
LinkedHashSet<Integer> b = buckets.get(e[1]);
b.remove(key);
if (b.isEmpty()) { buckets.remove(e[1]); if (minF == e[1]) minF++; }
e[1]++;
buckets.computeIfAbsent(e[1], k -> new LinkedHashSet<>()).add(key);
}
public int get(int key) {
if (!kv.containsKey(key)) return -1;
touch(key);
return kv.get(key)[0];
}
public void put(int key, int value) {
if (cap == 0) return;
if (kv.containsKey(key)) { kv.get(key)[0] = value; touch(key); return; }
if (kv.size() == cap) {
LinkedHashSet<Integer> b = buckets.get(minF);
int old = b.iterator().next();
b.remove(old);
if (b.isEmpty()) buckets.remove(minF);
kv.remove(old);
}
kv.put(key, new int[]{value, 1});
buckets.computeIfAbsent(1, k -> new LinkedHashSet<>()).add(key);
minF = 1;
}
}
type lfuEntry struct {
key, val, freq int
}
type LFUCache struct {
cap, minFreq int
items map[int]*list.Element // key -> its element in lists[freq]
lists map[int]*list.List // freq -> entries, most recently used at the front
}
func Constructor(capacity int) LFUCache {
return LFUCache{cap: capacity, items: map[int]*list.Element{}, lists: map[int]*list.List{}}
}
func (this *LFUCache) touch(el *list.Element) { // one more use: move to the next frequency list
e := el.Value.(*lfuEntry)
old := this.lists[e.freq]
old.Remove(el)
if old.Len() == 0 {
delete(this.lists, e.freq)
if this.minFreq == e.freq {
this.minFreq++
}
}
e.freq++
if this.lists[e.freq] == nil {
this.lists[e.freq] = list.New()
}
this.items[e.key] = this.lists[e.freq].PushFront(e)
}
func (this *LFUCache) Get(key int) int {
el, ok := this.items[key]
if !ok {
return -1
}
e := el.Value.(*lfuEntry)
this.touch(el)
return e.val
}
func (this *LFUCache) Put(key int, value int) {
if this.cap == 0 {
return
}
if el, ok := this.items[key]; ok {
e := el.Value.(*lfuEntry)
e.val = value
this.touch(el)
return
}
if len(this.items) == this.cap { // evict the LRU entry among the least frequent
l := this.lists[this.minFreq]
victim := l.Back()
l.Remove(victim)
if l.Len() == 0 {
delete(this.lists, this.minFreq)
}
delete(this.items, victim.Value.(*lfuEntry).key)
}
if this.lists[1] == nil {
this.lists[1] = list.New()
}
this.items[key] = this.lists[1].PushFront(&lfuEntry{key: key, val: value, freq: 1})
this.minFreq = 1
}