LFU Cache

Hard

Topics
Hash TableLinked ListDesignCounting

Design a cache that evicts the least frequently used key when it is full.

LFUCache(capacity) creates the cache. get(key) returns the value or -1. put(key, value) inserts or updates.

Both get and put count as a use of the key. When the cache is full and a new key is inserted, evict the key with the smallest use count; if several tie, evict the least recently used among them.

Example 1

returnsLFUCache(2)put(1, 1)put(2, 2)get(1)1put(3, 3)get(2)-1get(3)3put(4, 4)get(1)-1get(3)3get(4)4
When the cache is full, the key evicted is the one used fewest times — and among keys tied on that count, the one used longest ago. Both get and put count as a use, including a put that merely overwrites. A get on an absent or evicted key answers -1.
Calls run top to bottom; the arrow shows what each one returns.
Input:  operations = ["LFUCache","put","put","get","put","get","get","put","get","get","get"], values = [[2],[1,1],[2,2],[1],[3,3],[2],[3],[4,4],[1],[3],[4]]
Output: [null,null,null,1,null,-1,3,null,-1,3,4]
Explanation: Inserting 3 evicts 2, which had been used once while 1 had been used twice. Inserting 4 then evicts 1.

Constraints

  • 1 <= capacity <= 10^4
  • 0 <= key, value <= 10^9
  • At most 2 * 10^5 calls to get and put.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Eviction needs the smallest use count, so the frequencies have to be ordered — but scanning for the minimum on every eviction is what makes the naive version slow.

The key observation is that the minimum frequency only ever moves in two ways: it resets to 1 when a new key is inserted, and it can only increase by one when the last key at the current minimum is promoted. So it can be tracked in a single variable rather than searched for.

Ties are broken by recency, which means each frequency needs its own recency-ordered bucket rather than a plain set.

Approach

  1. Keep a map from key to its value and use count, and a map from use count to the keys at that count, held in insertion order so the oldest is identifiable.
  2. Track minFreq, the smallest count currently present.
  3. On a use (get, or a put of an existing key), move the key from its bucket to the next one up. If its old bucket was minFreq and is now empty, raise minFreq by one.
  4. On inserting a new key when full, drop the oldest key in the minFreq bucket, then insert the newcomer at count 1 and set minFreq = 1.

Walkthrough

capacity 2

put(1,1)   {1:v=1,f=1}                 minFreq=1
put(2,2)   {1:f=1, 2:f=1}              minFreq=1
get(1)     -> 1, key 1 promoted to f=2  minFreq=1 (2 still at 1)
put(3,3)   full: evict lowest count -> key 2
           {1:f=2, 3:f=1}              minFreq=1
get(2)     -> -1 (evicted)
get(3)     -> 3, key 3 promoted to f=2  minFreq=2

Complexity

  • Time — O(1): every operation is a fixed number of map and ordered-bucket updates; no search for the minimum.
  • Space — O(capacity): one entry per stored key across the value, frequency and bucket maps.

Common Pitfalls

  • Forgetting that put on an existing key is also a use — it must promote the key, not just overwrite the value.
  • Setting minFreq to 1 only on insertion is right; recomputing it by scanning the buckets reintroduces the cost the structure exists to avoid.
  • A tie on count must be broken by recency, so each bucket has to preserve insertion order rather than being an unordered set.

Full Solution — all languages

class LFUCache:
    def __init__(self, capacity):
        from collections import defaultdict, OrderedDict
        self.cap = capacity
        self.val = {}
        self.freq = {}
        self.buckets = defaultdict(OrderedDict)
        self.minFreq = 0

    def _touch(self, key):
        f = self.freq[key]
        del self.buckets[f][key]
        if not self.buckets[f]:
            del self.buckets[f]
            if self.minFreq == f:
                self.minFreq = f + 1
        self.freq[key] = f + 1
        self.buckets[f + 1][key] = None

    def get(self, key):
        if key not in self.val:
            return -1
        self._touch(key)
        return self.val[key]

    def put(self, key, value):
        if self.cap <= 0:
            return
        if key in self.val:
            self.val[key] = value
            self._touch(key)
            return
        if len(self.val) >= self.cap:
            old, _ = self.buckets[self.minFreq].popitem(last=False)
            if not self.buckets[self.minFreq]:
                del self.buckets[self.minFreq]
            del self.val[old]
            del self.freq[old]
        self.val[key] = value
        self.freq[key] = 1
        self.buckets[1][key] = None
        self.minFreq = 1
SensAI
Beta
Tap the mic to stop voice mode