Data Structures · Visualization
LFU Cache: Get
LFU Cache
Getting a value looks it up in the hash table, and — since accessing it counts as a use — increases its frequency count and moves it into the group of items sharing that new, higher frequency. Time: O(1) with a proper frequency-bucket design. Space: O(1) per operation.
Big-O: get / put both O(1).
LFU Cache: Get
LFU CacheGetting a value looks it up in the hash table, and — since accessing it counts as a use — increases its frequency count and moves it into the group of items sharing that new, higher frequency. If the key isn't present, the get reports a miss without affecting anything.
How Get Works
- Look up the key in the hash table.
- If the key doesn't exist, return 'not found' (a cache miss).
- If it exists, retrieve its value.
- Increase its frequency count by 1, and move it into its new frequency group.
- Return the value.
Get Worked Example
Input: Get(1) where item 1 currently has frequency 2
- Look up key 1 → found, value A
- Increase frequency: 2 -> 3
- Move item 1 from the 'frequency 2' group to the 'frequency 3' group
Output: Returns A; item 1's frequency is now 3
Press ▶ Run to watch it step by step.
from collections import defaultdict
class LFUCache:
def __init__(self, cap):
self.cap = cap
self.val = {} # key -> value
self.freq = {} # key -> frequency
self.buckets = defaultdict(dict) # freq -> {key: None}
def get(self, key):
if key not in self.val:
return -1
self._bump(key)
return self.val[key]
def _bump(self, key):
f = self.freq[key]
del self.buckets[f][key]
self.freq[key] = f + 1
self.buckets[f + 1][key] = None
def put(self, key, value):
if self.cap == 0:
return
if key in self.val:
self.val[key] = value
self._bump(key)
return
if len(self.val) >= self.cap:
# evict from the lowest-frequency bucket
for f in sorted(self.buckets):
if self.buckets[f]:
victim = next(iter(self.buckets[f]))
del self.buckets[f][victim]
del self.val[victim]
del self.freq[victim]
break
self.val[key] = value
self.freq[key] = 1
self.buckets[1][key] = None
# example: get key=1Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Get Time & Space Complexity
When to Use Get
- Reading a frequently accessed cached resource, reinforcing that it should stay cached
- Updating popularity tracking for cached content
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.