Data Structures · Visualization
LFU Cache: Introduction
LFU Cache
An LFU (Least Frequently Used) cache stores a limited number of items and, when full, evicts whichever item has been accessed the fewest number of times — rather than the one used longest ago (which is what LRU does). Time: O(1) for both get and put, with a well-designed frequency-bucket structure. Space: O(capacity).
Big-O: get / put both O(1).
LFU Cache: Introduction
LFU CacheAn LFU (Least Frequently Used) cache stores a limited number of items and, when full, evicts whichever item has been accessed the fewest number of times — rather than the one used longest ago (which is what LRU does). If there's a tie in frequency, it's common to fall back to evicting the least recently used among the tied items. It's typically implemented using a hash table for lookups plus a structure that groups items by their access frequency.
How LFU Cache: Introduction Works
- Set a fixed capacity for how many items the cache can hold.
- Track a usage count (frequency) for every item, starting at 1 when first added.
- Every time an item is accessed, increase its frequency count.
- When the cache is full and a new item must be added, evict the item with the lowest frequency count (breaking ties by least recently used).
LFU Cache: Introduction Worked Example
Input: Capacity 2. Put(1,A), Put(2,B), Get(1), Get(1), Put(3,C)
- Put(1,A) → freq(1)=1
- Put(2,B) → freq(1)=1, freq(2)=1
- Get(1) → freq(1)=2
- Get(1) → freq(1)=3
- Put(3,C) → cache full, evict lowest frequency: item 2 (freq=1)
Output: Final cache: {1:A (freq 3), 3:C (freq 1)} (2 was evicted)
Press ▶ Run to watch it step by step.
from collections import OrderedDict
# Hash map for O(1) lookups + an order
# structure to decide WHAT to evict.
# example: intro key=1 value=ALFU Cache: Introduction Time & Space Complexity
When to Use LFU Cache: Introduction
- Caching systems where some items are accessed far more often than others long-term
- Content delivery networks caching consistently popular content
- Database buffer pools that want to keep 'hot' data resident
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.