Animate LFU cache replacement with live frequency counters. See how the least frequently used item is evicted when the cache is full.
About this algorithm
An LFU cache counts how many times each item has been used and, when it is full, evicts the item with the smallest count. Popular items build up a high count and stay; items used once are the first to go. When two items share the lowest count, a tie-break picks which one leaves.
Use LFU when popularity is stable over time: a content delivery network holding the same few hit videos all day, or a lookup table where some keys are read thousands of times and others once. LRU reacts faster when interest shifts, because LFU keeps a once-famous item long after nobody wants it, and a brand new item starts at count 1 and is easy to evict. FIFO and Clock do not track counts at all. MRU only makes sense for looping scans. On LeetCode this is problem 460, LFU Cache, where every operation must run in constant time.
Each cached key carries a use count that starts at 1 when it enters the cache.
A hit leaves the item in the cache and raises its count by one. Nothing is evicted.
Look for the smallest count in the cache. If several keys share it, break the tie: this page removes the one that entered the cache first. Evict that key.
The requested key goes in with a count of 1. A key that was evicted earlier and comes back starts again at 1; its old count is forgotten.
The page requests 1 2 3 4 1 2 5 1 2 3 4 5 into four slots and shows each count beside its key. After the first four misses every key has count 1. The hits on 1 and 2 raise them to 2. When 5 arrives, 3 and 4 tie at count 1 and 3 came in earlier, so 3 is evicted. The next 1 and 2 hit again and climb to 3 each. From here the two popular keys are safe and the other two slots churn: 3 evicts 4, 4 evicts 5, and 5 evicts 3, each newcomer entering at count 1. The run ends with 4 hits and 8 misses, a 33% hit rate, and 1 and 2 still in the cache with count 3.
This visualizer breaks a tie on the lowest count by evicting the key that entered the cache first. LeetCode 460 asks for the least recently used of the tied keys instead. On this sequence the two rules pick the same victims, because none of the tied keys was ever hit, but on other inputs they can differ.
Scanning for the smallest count costs time proportional to the cache size. The fast version keeps a list of keys for each count plus a minFreq variable. A hit moves its key from bucket f to bucket f + 1 and raises minFreq if bucket f is now empty; an eviction takes a key from the minFreq bucket; an insert resets minFreq to 1.
Time: with a bucket per count and a minFreq pointer, a hit moves one key to the next bucket and an eviction removes from one known bucket, both constant time; the scan this page animates costs O(capacity). Space: one count per key, and the buckets together hold each key once.