LFU Cache
LFU Cache is LeetCode 460 (Hard). Design a least frequently used cache that holds at most capacity keys and supports two calls:
get(key): return the key's value, or-1if it is not in the cache.put(key, value): insert the key or update its value. If a new key arrives while the cache is full, first remove the least frequently used key. If several keys share the lowest use count, remove the one used longest ago.
Every key has a use counter. It is 1 when the key is inserted, and each get or put on the key adds 1. Both calls must run in O(1) average time, over up to 2 × 10⁵ calls.
- 1 <= capacity <= 10⁴
- 0 <= key <= 10⁵
- 0 <= value <= 10⁹
- At most 2 × 10⁵ calls will be made to get and put.
Intuition
Eviction needs two facts at once: the smallest use count, and the oldest key among those with that count. One sorted order cannot give both, so put keys into buckets by use count, and keep each bucket in the order the keys arrived.
- Bucket: a use count, mapped to its keys, oldest first.
- Use: a key moves from bucket
fto the back of bucketf + 1, so it becomes the newest key with its new count. - Smallest count: one number,
min_freq. A use can only empty bucketfby moving its key tof + 1, and a new key always starts at 1, somin_freqeither goes up by one or resets to 1.
A cache that must evict by one rule and break ties by another, both in O(1), usually needs a hash map for lookup plus one ordered list per value of the first rule.
Approach
Before reading on, decide what you would scan to find the key to evict, then ask what you could store so that the scan is never needed. Aim for O(1) per call.
Keep a key table and count buckets
vals maps each key to [value, count]. buckets maps each count to an OrderedDict of keys, oldest first. An ordered dict, like a doubly linked list with a key-to-node map, removes any key and pops the oldest in O(1).
Move a key up on every use
_bump deletes the key from buckets[f], adds it at the end of buckets[f + 1], and stores the new count. Adding at the end makes it the newest key with that count, which is what decides later ties.
Raise min_freq when its bucket empties
If buckets[f] is now empty, delete it, and if f was min_freq, set min_freq = f + 1. The key that just moved sits in bucket f + 1, so that bucket is never empty.
Treat an update as a use
get on a missing key returns -1; otherwise it bumps the key and returns the value. put on a key already in the cache changes the value and bumps it too, and removes nothing, because the number of keys does not grow.
Evict, then insert a new key
If the cache is full, pop the oldest key from buckets[min_freq] and delete it from vals. Then store the new key with count 1 at the end of buckets[1] and set min_freq = 1, since no key can have a smaller count.
Code in Python, C++ and Java
get results, in order, are [1, -1, 3, -1, 3, 4].get results, in order, are [-1, 10].get results, in order, are [1, 1, -1, 2].Common pitfalls
Setting min_freq to 1 before evicting
self.min_freq = 1
if len(self.vals) == self.cap:
old, _ = self.buckets[self.min_freq].popitem(last=False)if len(self.vals) == self.cap:
old, _ = self.buckets[self.min_freq].popitem(last=False)
...
self.min_freq = 1With capacity 1, put(1, 1) then get(1) leaves key 1 alone in bucket 2. put(2, 2) must evict from bucket 2, but resetting first sends it to bucket 1, which is empty, and popitem raises an error.
Updating a value without counting the use
if key in self.vals:
self.vals[key][0] = value
returnif key in self.vals:
self.vals[key][0] = value
self._bump(key)
returnWith capacity 2: put(1, 1), put(2, 2), put(1, 10), put(3, 3). Key 1 has been used twice, so key 2 must go, and get(2) returns -1. Skipping the bump leaves both at count 1, so the older key 1 is evicted instead.
Evicting before checking whether the key exists
if len(self.vals) == self.cap:
evict()
if key in self.vals:
...if key in self.vals:
...
return
if len(self.vals) == self.cap:
evict()With capacity 2: put(1, 1), put(2, 2), put(2, 20). The update does not add a key, but the full-cache check fires first and throws key 1 out, so get(1) returns -1 instead of 1.
Edge cases
Every new key evicts the only key, however often it was used: after put(1, 1), get(1), get(1), a put(2, 2) still removes key 1 from bucket 3, and min_freq drops back to 1.
Complexity
vals holds at most capacity keys, and every key sits in exactly one bucket.LFU Cache FAQ
How is LFU different from LRU?
LRU Cache (LeetCode 146) evicts the key unused for the longest time and needs one ordered list; LFU evicts the key used the fewest times and looks at recency only to break ties, so it needs one ordered list per use count.
Can a heap or a TreeMap find the key to evict?
Yes, but not in O(1). A min-heap ordered by (count, last use) or a Java TreeMap from count to keys costs O(log n) per change, and every get changes a count. It passes the time limit, but it misses the O(1) requirement.