Problem
Design a cache with a fixed capacity that evicts the least frequently used key when it is full. If several keys share that lowest frequency, evict the least recently used among them. get and put should be average O(1). Missing keys return -1.
Original: LeetCode 460: LFU Cache.
Examples
Example 1
`LFUCache: LFUCache(2), put(1, 1), put(2, 2), get(1), put(3, 3), get(2), get(3), put(4, 4), get(1), get(3), get(4)``[null, null, null, 1, null, -1, 3, null, -1, 3, 4]`Constraints
1 <= capacity <= 10^40 <= key <= 10^50 <= value <= 10^9- At most
2 * 10^5calls will be made togetandput.
Hints
Hint 1
Both get and put count as a use and increase the frequency. Updating an existing key also counts as a use and must not grow the size. Capacity can be zero.
Hint 2
LFU with an LRU tie-break is a frequency map plus, for each frequency, an LRU list or an insertion-ordered set.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Scan the whole cache for the minimum frequency, which is linear.
Optimal. Three structures: key to (value, freq), freq to an ordered key set, and the current minimum frequency. When a key's old frequency list becomes empty and it was the minimum, increment minFreq.
Alternative. A balanced tree of (freq, lastUsed, key) also works, but operations become logarithmic.
Complexity
- Time
- O(1)
get and put are average O(1) time, because a LinkedHashSet or OrderedDict inserts, deletes and takes the oldest key in constant time. Space is O(capacity).
- Space
- O(capacity)
Code
from collections import defaultdict, OrderedDict
class LFUCache:
def __init__(self, capacity: int) -> None:
self.capacity = capacity
self.min_freq = 0
self.values: dict[int, int] = {}
self.freqs: dict[int, int] = {}
self.by_freq: dict[int, OrderedDict[int, None]] = defaultdict(OrderedDict)
def get(self, key: int) -> int:
if key not in self.values:
return -1
self._bump(key)
return self.values[key]
def put(self, key: int, value: int) -> None:
if self.capacity == 0:
return
if key in self.values:
self.values[key] = value
self._bump(key)
return
if len(self.values) == self.capacity:
self._evict()
self.values[key] = value
self.freqs[key] = 1
self.by_freq[1][key] = None
self.min_freq = 1
def _bump(self, key: int) -> None:
freq = self.freqs[key]
bucket = self.by_freq[freq]
del bucket[key]
if not bucket:
del self.by_freq[freq]
if self.min_freq == freq:
self.min_freq += 1
self.freqs[key] = freq + 1
self.by_freq[freq + 1][key] = None
def _evict(self) -> None:
bucket = self.by_freq[self.min_freq]
evict, _ = bucket.popitem(last=False)
if not bucket:
del self.by_freq[self.min_freq]
del self.values[evict]
del self.freqs[evict]
if __name__ == "__main__":
c = LFUCache(2)
c.put(1, 1)
c.put(2, 2)
assert c.get(1) == 1
c.put(3, 3)
assert c.get(2) == -1
assert c.get(3) == 3
c.put(4, 4)
assert c.get(1) == -1 and c.get(3) == 3 and c.get(4) == 4
print("ok")import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
public class LfuCache {
private final int capacity;
private int minFreq = 0;
private final Map<Integer, Integer> values = new HashMap<>();
private final Map<Integer, Integer> freqs = new HashMap<>();
private final Map<Integer, LinkedHashSet<Integer>> byFreq = new HashMap<>();
LfuCache(int capacity) {
this.capacity = capacity;
}
int get(int key) {
if (!values.containsKey(key)) return -1;
bump(key);
return values.get(key);
}
void put(int key, int value) {
if (capacity == 0) return;
if (values.containsKey(key)) {
values.put(key, value);
bump(key);
return;
}
if (values.size() == capacity) evict();
values.put(key, value);
freqs.put(key, 1);
byFreq.computeIfAbsent(1, k -> new LinkedHashSet<>()).add(key);
minFreq = 1;
}
private void bump(int key) {
int freq = freqs.get(key);
var set = byFreq.get(freq);
set.remove(key);
if (set.isEmpty()) {
byFreq.remove(freq);
if (minFreq == freq) minFreq++;
}
freqs.put(key, freq + 1);
byFreq.computeIfAbsent(freq + 1, k -> new LinkedHashSet<>()).add(key);
}
private void evict() {
var set = byFreq.get(minFreq);
int evict = set.iterator().next();
set.remove(evict);
if (set.isEmpty()) byFreq.remove(minFreq);
values.remove(evict);
freqs.remove(evict);
}
public static void main(String[] args) {
var c = new LfuCache(2);
c.put(1, 1);
c.put(2, 2);
if (c.get(1) != 1) throw new AssertionError();
c.put(3, 3);
if (c.get(2) != -1) throw new AssertionError();
if (c.get(3) != 3) throw new AssertionError();
c.put(4, 4);
if (c.get(1) != -1 || c.get(3) != 3 || c.get(4) != 4) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official sample with capacity 2: put(1,1), put(2,2), get(1) returns 1, put(3,3) evicts key 2, get(2) returns -1, get(3) returns 3, put(4,4) evicts key 1, then get(1) is -1, get(3) is 3 and get(4) is 4.
- After a bump, if the old frequency list is empty and it was minFreq, minFreq increases. A brand-new key always starts at frequency 1, so minFreq is reset to 1.
- A cache with capacity 0 ignores every put.
Follow-ups
- LRU Cache is the same idea with a single list, because every key is treated as having the same frequency.
Interview script
"I store the value and the frequency of each key, and I keep an LRU list per frequency. A use moves the key from frequency f to f+1. Eviction takes the oldest key in the lowest frequency list. That gives O(1) operations and the LRU tie-break."
Source: LeetCode 460: LFU Cache Source: Java SE 17 API: LinkedHashSet
Sources (2)
- LeetCode 460: LFU Cacheleetcode.com
- Java SE 17 API: LinkedHashSetdocs.oracle.com