A cache that evicts the least frequently used key in O(1): a map from key to node, plus one list per use count and a pointer to the lowest count.
▼The problem
LeetCode 460 (Hard). Implement LFUCache(capacity) with get(key) (the value, or -1 if the key is missing) and put(key, value) (insert or update). When a put of a new key finds the cache full, evict the least frequently used key; on a tie, the least recently used of them. A get or put of an existing key counts as a use. Both calls must run in O(1) average time.
Example (LeetCode's): LFUCache(2), put(1,1), put(2,2), get(1) → 1, put(3,3) evicts 2 (one use against two), get(2) → -1, get(3) → 3 (bucket 1 empties, the minimum rises to 2), put(4,4) evicts 1 (1 and 3 both have two uses; 1 is older), get(1) → -1, get(3) → 3, get(4) → 4.
The solution
from collections import defaultdict, OrderedDict
class LFUCache:
def __init__(self, capacity):
self.cap, self.min_freq = capacity, 0
self.node = {} # key -> [value, freq]
self.bucket = defaultdict(OrderedDict) # oldest first
def touch(self, key): # one more use
f = self.node[key][1]
del self.bucket[f][key]
if f == self.min_freq and not self.bucket[f]:
self.min_freq += 1
self.node[key][1] = f + 1
self.bucket[f + 1][key] = None
def get(self, key):
if key not in self.node: return -1
self.touch(key)
return self.node[key][0]
def put(self, key, value):
if key in self.node:
self.node[key][0] = value
return self.touch(key)
if len(self.node) == self.cap: # full: evict
old, _ = self.bucket[self.min_freq].popitem(last=False)
del self.node[old]
self.node[key] = [value, 1]
self.bucket[1][key] = None
self.min_freq = 1Transcript
LFU Cache. A cache holds a fixed number of keys. Get returns a key's value, or minus one if it isn't there. Put stores a value. Every get or put of a key counts as one use. When the cache is full and a new key arrives, the key with the fewest uses is evicted; on a tie, the one used least recently. Both calls must run in constant time.
Take a cache with room for two. Put one, put two, then get one: key one now has two uses. Put three: the cache is full, and two has just one use, so two is evicted. Get two returns minus one.
The simple way keeps a use count and a last-used time on every key. To evict, it scans every key for the lowest count, then the oldest time. That scan costs order n on every put.
The fix: group keys by frequency. Keep one bucket per use count, each ordered from oldest to newest, and remember the smallest count that has any keys. A use moves a key out of its bucket to the back of the next bucket up. To evict, take the front of the smallest bucket: the fewest uses, and among those, the oldest.
In code: a map from each key to its value and count, an ordered dictionary for each count, and the minimum. Touch moves a key up one bucket; if that leaves the minimum bucket empty, the minimum goes up by one. A new key starts with one use, so the minimum resets to one.
Back to the example. Get three moves three up to bucket two. Bucket one is now empty, so the minimum rises to two. Put four: one and three tie at two uses, and one is older, so one goes. Four starts in bucket one. Then get one returns minus one, and get three and get four find their values.
Each call is a few hash lookups and one move at the front or back of a bucket, so both run in constant time. Space grows with the capacity.
Count every use, bucket by count, evict the oldest of the least used. That's LFU Cache.