LFU Cache (LeetCode 460): Solution and Explanation

Hard
Hash Table
Linked List
Design
Doubly Linked List

Build a cache with a fixed capacity that evicts the key used the fewest times when it is full. If several keys share that lowest use count, the one touched longest ago goes first. Both get and put must run in constant time.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

A naive LFU cache keeps a count per key and, on eviction, scans every key for the smallest count and oldest timestamp. That costs O(capacity) per eviction. A heap keyed on (count, time) brings it to O(log capacity), but updating a key's count inside a heap is awkward. To reach O(1) we need a structure where the victim is always sitting at a known spot.

The trick is to group keys by frequency. For each frequency value keep an insertion-ordered collection of the keys that currently have it. Within a bucket, the first key is the least recently used one, which is exactly the tie breaker the problem asks for. Then all we need is to remember the smallest frequency that has a non-empty bucket, minFreq, and the eviction victim is the first key in freqMap[minFreq].

Moving a key from frequency f to f + 1 is a delete from one bucket and an append to another, both O(1) with an ordered dict or a doubly linked list. minFreq is also easy to maintain: it only rises when the bucket at minFreq empties during a get, and then it rises by exactly one because the key we just moved landed in f + 1. When a brand new key is inserted its frequency is 1, so minFreq resets to 1.

Approach: Frequency buckets with a min frequency pointer

  1. Keep cache mapping each key to (value, freq), freqMap mapping each frequency to an OrderedDict of keys, and minFreq.
  2. On get, return -1 for a missing key. Otherwise remove the key from freqMap[freq], delete that bucket if it is now empty, and bump minFreq if the emptied bucket was the minimum.
  3. Still in get, store (value, freq + 1) in cache, append the key to freqMap[freq + 1] and return the value.
  4. On put with a capacity of zero, do nothing.
  5. If the key already exists, overwrite its value and call get to bump its frequency.
  6. If the cache is full, take the first key of freqMap[minFreq] (the least recently used among the least frequent), remove it from the bucket and from cache.
  7. Insert the new key with frequency 1, append it to freqMap[1] and set minFreq = 1.

Step-by-step example

capacity = 2; put(1,1), put(2,2), get(1), put(3,3), get(2), get(3)
  1. put(1,1) and put(2,2): both keys have frequency 1, freqMap[1] holds [1, 2] in that order and minFreq is 1.
  2. get(1) returns 1. Key 1 moves to freqMap[2], leaving freqMap[1] = [2]. The bucket is not empty, so minFreq stays 1.
  3. put(3,3): the cache is full, so evict the first key in freqMap[1], which is key 2. Insert key 3 with frequency 1 and set minFreq to 1.
  4. get(2) returns -1 because key 2 was evicted.
  5. get(3) returns 3. Key 3 moves to frequency 2, freqMap[1] empties and is deleted, and minFreq rises to 2. freqMap[2] now holds [1, 3].

Code: Python, Java, C++

1class LFUCache:
2    def __init__(self, capacity: int):
3        self.capacity = capacity
4        self.cache = {}  # key -> (value, freq)
5        self.freqMap = defaultdict(OrderedDict)  # freq -> {key: None}
6        self.minFreq = 0
7
8    def get(self, key: int) -> int:
9        if key not in self.cache:
10            return -1
11
12        value, freq = self.cache[key]
13        del self.freqMap[freq][key]
14        if not self.freqMap[freq]:
15            del self.freqMap[freq]
16            if self.minFreq == freq:
17                self.minFreq += 1
18
19        self.cache[key] = (value, freq + 1)
20        self.freqMap[freq + 1][key] = None
21        return value
22
23    def put(self, key: int, value: int) -> None:
24        if self.capacity <= 0:
25            return
26
27        if key in self.cache:
28            self.cache[key] = (value, self.cache[key][1])
29            self.get(key)  # Update frequency
30            return
31
32        if len(self.cache) >= self.capacity:
33            # Evict LFU key
34            evictKey = next(iter(self.freqMap[self.minFreq]))
35            del self.freqMap[self.minFreq][evictKey]
36            if not self.freqMap[self.minFreq]:
37                del self.freqMap[self.minFreq]
38            del self.cache[evictKey]
39
40        self.cache[key] = (value, 1)
41        self.freqMap[1][key] = None
42        self.minFreq = 1

Time and space complexity

Time

O(1) per operation

Every step is a dict lookup, an ordered dict insert or delete, or reading the first key of a bucket, all of which are constant time on average.

Space

O(capacity)

Each stored key appears once in cache and once in exactly one frequency bucket, and empty buckets are deleted.

Other approaches

Min heap keyed by (frequency, timestamp) (time O(log n) per operation, space O(n))

Push a new heap entry on every access and lazily discard stale entries when evicting. It is easier to reason about but costs a log factor and lets the heap grow with the number of operations unless you rebuild it.

Common mistakes

  • Resetting minFreq to something other than 1 when inserting a new key. A new key always has the lowest possible frequency.
  • Evicting before checking whether the key already exists, which throws out a different key even though updating in place needs no room.
  • Forgetting the capacity zero case, where next(iter(self.freqMap[self.minFreq])) on an empty bucket raises an error.
  • Using a plain set for buckets, which loses the recency order needed to break ties between keys with equal frequency.

Frequently asked questions

What is the difference between an LRU and an LFU cache?

LRU evicts the key that was used longest ago, regardless of how often. LFU evicts the key used the fewest times, and only uses recency to break ties. LFU keeps popular keys around even if they were not touched recently.

Why does minFreq only ever increase by one in get?

A get moves one key from frequency f to f + 1. If that emptied the bucket at minFreq, the moved key now sits at f + 1, so that bucket is guaranteed to be non-empty and becomes the new minimum.

How do you get O(1) LFU in Java or C++ without OrderedDict?

Use a LinkedHashSet per frequency in Java, or a list per frequency plus a map from key to its list iterator in C++. Both give constant time removal of an arbitrary key and constant time access to the oldest key.