Data Structures · Visualization
LFU Cache: Put
LFU Cache
Putting a value either updates an existing key (increasing its frequency, like a get) or inserts a brand-new key with a starting frequency of 1. Time: O(1) with a proper frequency-bucket design. Space: O(1) per operation.
Big-O: get / put both O(1).
LFU Cache: Put
LFU CachePutting a value either updates an existing key (increasing its frequency, like a get) or inserts a brand-new key with a starting frequency of 1. If inserting a new key would exceed the cache's capacity, the item with the lowest frequency is evicted first (using recency as a tiebreaker if multiple items share the lowest frequency).
How Put Works
- Check if the key already exists in the hash table.
- If it exists, update its value and increase its frequency count (moving it to the new frequency group).
- If it doesn't exist and the cache is at capacity, find the group with the lowest frequency and evict its least recently used item.
- Insert the new key with a frequency of 1, placing it in the 'frequency 1' group.
Put Worked Example
Input: Put(3,C) on a full cache where item 2 has the lowest frequency (1)
- Key 3 doesn't exist and cache is full
- Lowest frequency group is 'frequency 1', containing item 2
- Evict item 2
- Insert item 3 with frequency 1
Output: Item 2 evicted; item 3 added with frequency 1
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: put value=CBehind 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.
Put Time & Space Complexity
When to Use Put
- Adding new content to a cache that prioritizes keeping consistently popular items
- Managing limited cache space where popularity, not recency, matters most
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.