LFU Cache (LeetCode 460): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- Keep
cachemapping each key to(value, freq),freqMapmapping each frequency to anOrderedDictof keys, andminFreq. - On
get, return -1 for a missing key. Otherwise remove the key fromfreqMap[freq], delete that bucket if it is now empty, and bumpminFreqif the emptied bucket was the minimum. - Still in
get, store(value, freq + 1)incache, append the key tofreqMap[freq + 1]and return the value. - On
putwith a capacity of zero, do nothing. - If the key already exists, overwrite its value and call
getto bump its frequency. - 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 fromcache. - Insert the new key with frequency 1, append it to
freqMap[1]and setminFreq = 1.
Step-by-step example
capacity = 2; put(1,1), put(2,2), get(1), put(3,3), get(2), get(3)
- put(1,1) and put(2,2): both keys have frequency 1,
freqMap[1]holds [1, 2] in that order andminFreqis 1. - get(1) returns 1. Key 1 moves to
freqMap[2], leavingfreqMap[1] = [2]. The bucket is not empty, sominFreqstays 1. - 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 setminFreqto 1. - get(2) returns -1 because key 2 was evicted.
- get(3) returns 3. Key 3 moves to frequency 2,
freqMap[1]empties and is deleted, andminFreqrises 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 = 11class LFUCache {
2 private int capacity;
3 private int minFreq;
4 private Map<Integer, int[]> cache; // key -> [value, freq]
5 private Map<Integer, LinkedHashSet<Integer>> freqMap;
6
7 public LFUCache(int capacity) {
8 this.capacity = capacity;
9 this.minFreq = 0;
10 this.cache = new HashMap<>();
11 this.freqMap = new HashMap<>();
12 }
13
14 public int get(int key) {
15 if (!cache.containsKey(key)) return -1;
16
17 int[] entry = cache.get(key);
18 int value = entry[0], freq = entry[1];
19
20 freqMap.get(freq).remove(key);
21 if (freqMap.get(freq).isEmpty()) {
22 freqMap.remove(freq);
23 if (minFreq == freq) minFreq++;
24 }
25
26 entry[1] = freq + 1;
27 freqMap.computeIfAbsent(freq + 1, k -> new LinkedHashSet<>()).add(key);
28 return value;
29 }
30
31 public void put(int key, int value) {
32 if (capacity <= 0) return;
33
34 if (cache.containsKey(key)) {
35 cache.get(key)[0] = value;
36 get(key);
37 return;
38 }
39
40 if (cache.size() >= capacity) {
41 int evictKey = freqMap.get(minFreq).iterator().next();
42 freqMap.get(minFreq).remove(evictKey);
43 if (freqMap.get(minFreq).isEmpty()) {
44 freqMap.remove(minFreq);
45 }
46 cache.remove(evictKey);
47 }
48
49 cache.put(key, new int[]{value, 1});
50 freqMap.computeIfAbsent(1, k -> new LinkedHashSet<>()).add(key);
51 minFreq = 1;
52 }
53}1class LFUCache {
2 int capacity, minFreq;
3 unordered_map<int, pair<int, int>> cache; // key -> {value, freq}
4 unordered_map<int, list<int>> freqMap; // freq -> list of keys
5 unordered_map<int, list<int>::iterator> keyIter; // key -> iterator
6
7public:
8 LFUCache(int capacity) : capacity(capacity), minFreq(0) {}
9
10 int get(int key) {
11 if (cache.find(key) == cache.end()) return -1;
12
13 auto& [value, freq] = cache[key];
14 freqMap[freq].erase(keyIter[key]);
15 if (freqMap[freq].empty()) {
16 freqMap.erase(freq);
17 if (minFreq == freq) minFreq++;
18 }
19
20 freq++;
21 freqMap[freq].push_back(key);
22 keyIter[key] = --freqMap[freq].end();
23 return value;
24 }
25
26 void put(int key, int value) {
27 if (capacity <= 0) return;
28
29 if (cache.find(key) != cache.end()) {
30 cache[key].first = value;
31 get(key);
32 return;
33 }
34
35 if (cache.size() >= capacity) {
36 int evictKey = freqMap[minFreq].front();
37 freqMap[minFreq].pop_front();
38 if (freqMap[minFreq].empty()) freqMap.erase(minFreq);
39 cache.erase(evictKey);
40 keyIter.erase(evictKey);
41 }
42
43 cache[key] = {value, 1};
44 freqMap[1].push_back(key);
45 keyIter[key] = --freqMap[1].end();
46 minFreq = 1;
47 }
48};Time and space complexity
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.
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
minFreqto 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.