LFU Cache
LeetCode 460 · కఠినం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
freq → OrderedDict buckets + min_freq.
నేను LFU Cache (LeetCode 460) ను ఇలా పరిష్కరించాను — Design ప్యాటర్న్లోని ఒక కఠినం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, 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.
నేను ఎలా పరిష్కరించాను
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 — తరచూ అడిగే ప్రశ్నలు
LFU Cache వెనుక ఉన్న 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.
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.
LFU Cache యొక్క time, space complexity ఎంత?
Time: O(1) per operation. Space: O(capacity). (Accepted approach: Frequency buckets.)
LFU Cache లో సాధారణ పొరపాట్లు ఏమిటి?
Ties at the same frequency are broken by recency — hence the ordered buckets.