LFU Cache
LeetCode 460 · Hard · solution, intuition & step-by-step walkthrough
freq → OrderedDict buckets + min_freq.
This is how I solved LFU Cache (LeetCode 460), a hard problem from the Design pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Track three maps: key → value, key → frequency, and frequency → ordered keys (oldest first). Remember the smallest frequency in use; eviction takes the oldest key at that frequency.
Approach
- 1
get: move the key from bucket f to f+1; bump min_freq if bucket f emptied.
- 2
put existing: run get, then update the value.
- 3
put new: if full, pop the oldest key in the min_freq bucket.
- 4
Insert with frequency 1 and set min_freq = 1.
How I solved it
Frequency bucketsPythonO(1) per op
class LFUCache:
"""
#key2val map
#key2freq map
#freq2keys map
#maintain minfreq
"""
def __init__(self, capacity: int):
self.key2val = {}
self.key2freq = {}
self.freq2keys= defaultdict(collections.OrderedDict)
self.min_freq =0
self.capacity=capacity
def get(self, key: int) -> int:
#increase frequency if exists
if key in self.key2val:
old_freq = self.key2freq[key]
self.freq2keys[old_freq].pop(key)
#remove tombstone
if not self.freq2keys[old_freq]:
del self.freq2keys[old_freq]
self.key2freq[key]=old_freq+1
self.freq2keys[old_freq+1][key]=1
if self.min_freq not in self.freq2keys:
self.min_freq+=1
return self.key2val[key]
return -1
def put(self, key: int, value: int) -> None:
if self.capacity<=0:
return
#if key already exists in map - increase the frequency
if key in self.key2val:
self.get(key)
self.key2val[key]=value
return
if len(self.key2val)==self.capacity:
delkey,_ = self.freq2keys[self.min_freq].popitem(last=False)
del self.key2val[delkey]
del self.key2freq[delkey]
#latest item added
self.min_freq=1
self.key2val[key]=value
self.key2freq[key]=1
self.freq2keys[1][key]=1
# Your LFUCache object will be instantiated and called as such:
# obj = LFUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)LFU Cache — FAQ
What is the intuition behind LFU Cache?
Track three maps: key → value, key → frequency, and frequency → ordered keys (oldest first). Remember the smallest frequency in use; eviction takes the oldest key at that frequency.
How do you solve LFU Cache (LeetCode 460)?
1. get: move the key from bucket f to f+1; bump min_freq if bucket f emptied. 2. put existing: run get, then update the value. 3. put new: if full, pop the oldest key in the min_freq bucket. 4. Insert with frequency 1 and set min_freq = 1.
What is the time and space complexity of LFU Cache?
Time: O(1) per operation. Space: O(capacity). (Accepted approach: Frequency buckets.)
What are common mistakes in LFU Cache?
Ties at the same frequency are broken by recency — hence the ordered buckets.