15% off all plans & roadmaps Use code
See plansLFU Cache
- LeetCode 460
- Hard
- Design Patterns
- Design (General/Specific)
Updated
TL;DR: Design a cache that evicts the least frequently used key and breaks ties by least recent use, with O(1) get and put. Keep a map from each frequency to an ordered bucket of keys, and track the smallest frequency in use.
Problem
Design and implement a data structure for a Least Frequently Used (LFU) cache.
Implement the LFUCache class:
LFUCache(int capacity)initializes the object with thecapacityof the data structure.int get(int key)returns the value ofkeyif it is in the cache. Otherwise, it returns-1.void put(int key, int value)updates the value ofkeyif it is present. If it is not present, it insertskey. When the cache is full, it removes the least frequently used key before it inserts the new item. If two or more keys tie on frequency, it removes the least recently used key among them.
Each key has a use counter. A new key starts with a counter of 1 when put inserts it. The counter goes up by one each time get or put is called on that key while it is in the cache. The key with the smallest counter is the least frequently used key.
Both get and put must run in O(1) average time.
Example 1
Input: ["LFUCache", "put", "put", "get", "put", "get", "get", "put", "get", "get", "get"] [[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: The cache holds 2 keys. Putting key 3 evicts key 2, which has the smallest counter. Putting key 4 evicts key 1, because keys 1 and 3 tie at 2 and key 1 was used less recently.
Constraints
1 <= capacity <= 10^40 <= key <= 10^50 <= value <= 10^9- At most
2 * 10^5calls will be made togetandput.
Constraints that matter
- At most 2 * 10^5 calls with a capacity of up to 10^4 means a scan of the cache on every put costs up to 2 * 10^9 steps. Eviction must find the victim without a scan.
- Counters start at 1 and rise by exactly one per use. A key therefore only ever moves from bucket f to bucket f + 1, which keeps the bookkeeping small.
- Ties need recency. Two keys with the same counter must be ordered by last use, so each bucket has to keep insertion order.
- Values go up to 10^9 and keys up to 10^5, so you can store them in hash maps directly. No array indexed by key is needed.
Hints
Hint 1
This is a design problem.
Hint 2
Store each key with its value, its use counter, and the time of its last use.
Solution
Intuition
This is a design problem. Every operation must be O(1), but each eviction has to find the least frequent key and, among ties, the least recent one. A single scan cannot meet that bound, so the pattern to reach for is a hash map of frequency buckets, where each bucket keeps its keys in recency order.
Picture a set of numbered bins, one per use count, with people standing in arrival order inside each. The bin number is the frequency, the line order is recency, and eviction removes the person at the front of the lowest nonempty bin.
The key detail is that a counter only moves up by one per use. When a key is touched, it leaves bucket f and joins bucket f + 1. You only need to track one integer, the smallest counter that is currently non-empty. Each touch can update that integer in constant time.
It works because the least frequent key always sits in the bucket at minFreq. Inside that bucket, the first key has the oldest last use, since every touch appends the key to the end. Eviction therefore reads one front element and removes it.
Worked example
Input: capacity = 1, operations in order: put(1, 100), put(2, 200), get(2), put(3, 300), get(1), put(3, 350), get(3), get(1) Output: [null, null, null, 200, null, -1, null, 350, -1] Explanation: With capacity 1, every new key evicts the single key already stored. The get calls on key 2 and key 3 raise their counters, and the put on key 3 updates its value instead of evicting it. The two missing-key lookups return -1.
Approach 1: Brute force
Store each key with its value, its use counter, and the time of its last use. When a put needs room, scan every entry for the smallest pair of (counter, time). Each get and put touches only one entry, but eviction reads all of them.
Steps
- Keep a map from key to an entry that holds the value, the counter, and the last-use time.
- Keep a clock that goes up by one on every get and every put.
- For get, return -1 on a missing key. Otherwise raise its counter and set its time to the clock.
- For put on an existing key, set the value, raise the counter, and set the time.
- For put on a new key with a full cache, scan all entries for the smallest (counter, time) pair and delete it.
- Insert the new key with counter 1 and the current time.
Dry run
Trace on the example, capacity 1, clock starts at 0.
- put(1, 100): clock 1. Cache is empty, store key 1 with counter 1, time 1.
- put(2, 200): clock 2. The cache is full, and the scan finds only key 1, so delete it. Store key 2 with counter 1, time 2.
- get(2): clock 3. Counter becomes 2, time 3. Return 200.
- put(3, 300): clock 4. The scan finds only key 2, so delete it. Store key 3 with counter 1, time 4.
- get(1): clock 5. Key 1 is missing. Return -1.
- put(3, 350): clock 6. Key 3 exists. Value becomes 350, counter 2, time 6.
- get(3): clock 7. Counter becomes 3. Return 350.
- get(1): clock 8. Key 1 is missing. Return -1.
The outputs are null, null, 200, null, -1, null, 350, -1, which matches the expected output.
Complexity
| Time | O(C) per put on a full cache, O(1) per get |
|---|---|
| Space | O(C) |
Let C be the capacity. A get does one hash lookup and one field update, so it costs O(1). A put on a full cache scans all C entries before it inserts, so it costs O(C). Across 2 * 10^5 calls with C up to 10^4, the worst case is about 2 * 10^9 steps, which is too many. Space is O(C) because the map holds at most C entries.
PythonTested in our runner
class LFUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.clock = 0
self.data = {} # key -> [value, counter, last_used]
def get(self, key: int) -> int:
self.clock += 1
if key not in self.data:
return -1
entry = self.data[key]
entry[1] += 1
entry[2] = self.clock
return entry[0]
def put(self, key: int, value: int) -> None:
if self.capacity == 0:
return
self.clock += 1
if key in self.data:
entry = self.data[key]
entry[0] = value
entry[1] += 1
entry[2] = self.clock
return
if len(self.data) >= self.capacity:
# Full scan: smallest counter, then oldest last use
victim = min(self.data, key=lambda k: (self.data[k][1], self.data[k][2]))
del self.data[victim]
self.data[key] = [value, 1, self.clock]
JavaTested in our runner
import java.util.*;
class LFUCache {
private int capacity;
private int clock;
private Map<Integer, int[]> data = new HashMap<>(); // {value, counter, lastUsed}
public LFUCache(int capacity) {
this.capacity = capacity;
this.clock = 0;
}
public int get(int key) {
clock++;
int[] e = data.get(key);
if (e == null) return -1;
e[1]++;
e[2] = clock;
return e[0];
}
public void put(int key, int value) {
if (capacity == 0) return;
clock++;
int[] e = data.get(key);
if (e != null) {
e[0] = value;
e[1]++;
e[2] = clock;
return;
}
if (data.size() >= capacity) {
int victim = -1;
int[] best = null;
for (Map.Entry<Integer, int[]> en : data.entrySet()) {
int[] c = en.getValue();
if (best == null || c[1] < best[1] || (c[1] == best[1] && c[2] < best[2])) {
best = c;
victim = en.getKey();
}
}
data.remove(victim);
}
data.put(key, new int[]{value, 1, clock});
}
}
C++Tested in our runner
#include <unordered_map>
struct Entry {
int value;
int freq;
int last;
};
class LFUCache {
int capacity;
int clock;
std::unordered_map<int, Entry> data;
public:
LFUCache(int capacity) : capacity(capacity), clock(0) {}
int get(int key) {
clock++;
auto it = data.find(key);
if (it == data.end()) return -1;
it->second.freq++;
it->second.last = clock;
return it->second.value;
}
void put(int key, int value) {
if (capacity == 0) return;
clock++;
auto it = data.find(key);
if (it != data.end()) {
it->second.value = value;
it->second.freq++;
it->second.last = clock;
return;
}
if ((int)data.size() >= capacity) {
int victim = 0;
bool found = false;
Entry best{0, 0, 0};
for (const auto& kv : data) {
if (!found || kv.second.freq < best.freq ||
(kv.second.freq == best.freq && kv.second.last < best.last)) {
best = kv.second;
victim = kv.first;
found = true;
}
}
data.erase(victim);
}
data[key] = Entry{value, 1, clock};
}
};
JavaScriptTested in our runner
var LFUCache = function(capacity) {
this.capacity = capacity;
this.clock = 0;
this.data = new Map(); // key -> {value, freq, last}
};
/**
* @param {number} key
* @return {number}
*/
LFUCache.prototype.get = function(key) {
this.clock++;
const e = this.data.get(key);
if (e === undefined) return -1;
e.freq++;
e.last = this.clock;
return e.value;
};
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LFUCache.prototype.put = function(key, value) {
if (this.capacity === 0) return;
this.clock++;
const e = this.data.get(key);
if (e !== undefined) {
e.value = value;
e.freq++;
e.last = this.clock;
return;
}
if (this.data.size >= this.capacity) {
let victim = null;
let best = null;
for (const [k, c] of this.data) {
if (best === null || c.freq < best.freq || (c.freq === best.freq && c.last < best.last)) {
best = c;
victim = k;
}
}
this.data.delete(victim);
}
this.data.set(key, {value: value, freq: 1, last: this.clock});
};
GoTested in our runner
package main
type entry struct {
value int
freq int
last int
}
type LFUCache struct {
capacity int
clock int
data map[int]*entry
}
func Constructor(capacity int) LFUCache {
return LFUCache{capacity: capacity, data: make(map[int]*entry)}
}
func (this *LFUCache) get(key int) int {
this.clock++
e, ok := this.data[key]
if !ok {
return -1
}
e.freq++
e.last = this.clock
return e.value
}
func (this *LFUCache) put(key int, value int) {
if this.capacity == 0 {
return
}
this.clock++
if e, ok := this.data[key]; ok {
e.value = value
e.freq++
e.last = this.clock
return
}
if len(this.data) >= this.capacity {
victim := -1
var best *entry
for k, c := range this.data {
if best == nil || c.freq < best.freq || (c.freq == best.freq && c.last < best.last) {
best = c
victim = k
}
}
delete(this.data, victim)
}
this.data[key] = &entry{value, 1, this.clock}
}
C#Tested in our runner
using System.Collections.Generic;
public class LFUCache {
class Entry {
public int Value;
public int Freq;
public int Last;
}
private int capacity;
private int clock;
private Dictionary<int, Entry> data = new Dictionary<int, Entry>();
public LFUCache(int capacity) {
this.capacity = capacity;
}
public int get(int key) {
clock++;
if (!data.TryGetValue(key, out var e)) return -1;
e.Freq++;
e.Last = clock;
return e.Value;
}
public void put(int key, int value) {
if (capacity == 0) return;
clock++;
if (data.TryGetValue(key, out var e)) {
e.Value = value;
e.Freq++;
e.Last = clock;
return;
}
if (data.Count >= capacity) {
int victim = 0;
Entry best = null;
foreach (var kv in data) {
if (best == null || kv.Value.Freq < best.Freq ||
(kv.Value.Freq == best.Freq && kv.Value.Last < best.Last)) {
best = kv.Value;
victim = kv.Key;
}
}
data.Remove(victim);
}
data[key] = new Entry { Value = value, Freq = 1, Last = clock };
}
}
The Design (General/Specific) infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Design (General/Specific)
Part of Design Patterns
Approach 2: Frequency buckets with recency orderOptimalDesign (General/Specific)
What's slow in the brute force: eviction reads every entry to find the minimum. The insight that fixes it: a counter only rises by one per use, so a key only moves from bucket f to bucket f + 1. Keep one insertion-ordered bucket per counter and one integer for the smallest non-empty counter. The least frequent key is then in bucket minFreq, and the first key in that bucket is the least recently used.
Steps
- Keep vals (key to value), freq (key to counter), buckets (counter to an insertion-ordered set of keys), and minFreq.
- To touch a key, remove it from buckets[freq[key]]. If that bucket is now empty, delete it, and if its counter was minFreq, set minFreq to counter + 1.
- Raise freq[key] by one and append the key to buckets[new counter], which makes it the most recent in that bucket.
- For get, return -1 on a missing key. Otherwise touch the key and return its value.
- For put on an existing key, set the new value and touch the key.
- For put on a new key with a full cache, take the first key of buckets[minFreq], delete it from every map, and delete the bucket if it is now empty.
- Insert the new key with counter 1, append it to buckets[1], and set minFreq to 1.
Dry run
Trace on the example, capacity 1. Each row is one call. The bucket column lists keys from least recent to most recent.
| Step | Call | vals | freq | buckets | minFreq | Returns |
|---|---|---|---|---|---|---|
| 1 | put(1, 100) | {1: 100} | {1: 1} | {1: [1]} | 1 | null |
| 2 | put(2, 200) | {2: 200} | {2: 1} | {1: [2]} | 1 | null |
| 3 | get(2) | {2: 200} | {2: 2} | {2: [2]} | 2 | 200 |
| 4 | put(3, 300) | {3: 300} | {3: 1} | {1: [3]} | 1 | null |
| 5 | get(1) | {3: 300} | {3: 1} | {1: [3]} | 1 | -1 |
| 6 | put(3, 350) | {3: 350} | {3: 2} | {2: [3]} | 2 | null |
| 7 | get(3) | {3: 350} | {3: 3} | {3: [3]} | 3 | 350 |
| 8 | get(1) | {3: 350} | {3: 3} | {3: [3]} | 3 | -1 |
At step 2, the cache is full, so key 1 is evicted from bucket 1. At step 3, bucket 1 empties and minFreq moves to 2. The returns read down the last column give null, null, 200, null, -1, null, 350, -1, which matches the expected output.
Complexity
| Time | O(1) |
|---|---|
| Space | O(C) |
Let C be the capacity. Each get or put performs a fixed number of hash map reads, writes and deletes. It also performs a fixed number of appends and removals in one bucket, which are O(1) with a linked structure. Eviction reads only the first key of bucket minFreq, so time is O(1). Space is O(C) because the maps and buckets hold at most C keys in total.
PythonTested in our runner
from collections import OrderedDict, defaultdict
class LFUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.min_freq = 0
self.vals = {}
self.freq = {}
self.buckets = defaultdict(OrderedDict) # counter -> keys, LRU first
def _touch(self, key: int) -> None:
f = self.freq[key]
bucket = self.buckets[f]
del bucket[key]
if not bucket:
del self.buckets[f]
if self.min_freq == f:
self.min_freq = f + 1
self.freq[key] = f + 1
self.buckets[f + 1][key] = None # most recent goes last
def get(self, key: int) -> int:
if key not in self.vals:
return -1
self._touch(key)
return self.vals[key]
def put(self, key: int, value: int) -> None:
if self.capacity == 0:
return
if key in self.vals:
self.vals[key] = value
self._touch(key)
return
if len(self.vals) >= self.capacity:
bucket = self.buckets[self.min_freq]
victim, _ = bucket.popitem(last=False) # least recent in min bucket
if not bucket:
del self.buckets[self.min_freq]
del self.vals[victim]
del self.freq[victim]
self.vals[key] = value
self.freq[key] = 1
self.buckets[1][key] = None
self.min_freq = 1
JavaTested in our runner
import java.util.*;
class LFUCache {
private int capacity;
private int minFreq;
private Map<Integer, Integer> vals = new HashMap<>();
private Map<Integer, Integer> freq = new HashMap<>();
// LinkedHashSet keeps insertion order, so the first element is the LRU key
private Map<Integer, LinkedHashSet<Integer>> buckets = new HashMap<>();
public LFUCache(int capacity) {
this.capacity = capacity;
}
public int get(int key) {
if (!vals.containsKey(key)) return -1;
touch(key);
return vals.get(key);
}
public void put(int key, int value) {
if (capacity == 0) return;
if (vals.containsKey(key)) {
vals.put(key, value);
touch(key);
return;
}
if (vals.size() >= capacity) {
LinkedHashSet<Integer> bucket = buckets.get(minFreq);
int victim = bucket.iterator().next();
bucket.remove(victim);
if (bucket.isEmpty()) buckets.remove(minFreq);
vals.remove(victim);
freq.remove(victim);
}
vals.put(key, value);
freq.put(key, 1);
buckets.computeIfAbsent(1, k -> new LinkedHashSet<>()).add(key);
minFreq = 1;
}
private void touch(int key) {
int f = freq.get(key);
LinkedHashSet<Integer> bucket = buckets.get(f);
bucket.remove(key);
if (bucket.isEmpty()) {
buckets.remove(f);
if (minFreq == f) minFreq = f + 1;
}
freq.put(key, f + 1);
buckets.computeIfAbsent(f + 1, k -> new LinkedHashSet<>()).add(key);
}
}
C++Tested in our runner
#include <unordered_map>
#include <list>
#include <iterator>
class LFUCache {
int capacity;
int minFreq;
std::unordered_map<int, int> vals;
std::unordered_map<int, int> freq;
// front is the least recently used key in each bucket
std::unordered_map<int, std::list<int>> buckets;
std::unordered_map<int, std::list<int>::iterator> pos;
void touch(int key) {
int f = freq[key];
auto& bucket = buckets[f];
bucket.erase(pos[key]);
if (bucket.empty()) {
buckets.erase(f);
if (minFreq == f) minFreq = f + 1;
}
freq[key] = f + 1;
buckets[f + 1].push_back(key);
pos[key] = std::prev(buckets[f + 1].end());
}
public:
LFUCache(int capacity) : capacity(capacity), minFreq(0) {}
int get(int key) {
if (vals.count(key) == 0) return -1;
touch(key);
return vals[key];
}
void put(int key, int value) {
if (capacity == 0) return;
if (vals.count(key)) {
vals[key] = value;
touch(key);
return;
}
if ((int)vals.size() >= capacity) {
auto& bucket = buckets[minFreq];
int victim = bucket.front();
bucket.pop_front();
if (bucket.empty()) buckets.erase(minFreq);
pos.erase(victim);
vals.erase(victim);
freq.erase(victim);
}
vals[key] = value;
freq[key] = 1;
buckets[1].push_back(key);
pos[key] = std::prev(buckets[1].end());
minFreq = 1;
}
};
JavaScriptTested in our runner
var LFUCache = function(capacity) {
this.capacity = capacity;
this.minFreq = 0;
this.vals = new Map();
this.freq = new Map();
// Map keeps insertion order, so the first key is the LRU key
this.buckets = new Map();
};
LFUCache.prototype.touch = function(key) {
const f = this.freq.get(key);
const bucket = this.buckets.get(f);
bucket.delete(key);
if (bucket.size === 0) {
this.buckets.delete(f);
if (this.minFreq === f) this.minFreq = f + 1;
}
this.freq.set(key, f + 1);
if (!this.buckets.has(f + 1)) this.buckets.set(f + 1, new Map());
this.buckets.get(f + 1).set(key, true);
};
/**
* @param {number} key
* @return {number}
*/
LFUCache.prototype.get = function(key) {
if (!this.vals.has(key)) return -1;
this.touch(key);
return this.vals.get(key);
};
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LFUCache.prototype.put = function(key, value) {
if (this.capacity === 0) return;
if (this.vals.has(key)) {
this.vals.set(key, value);
this.touch(key);
return;
}
if (this.vals.size >= this.capacity) {
const bucket = this.buckets.get(this.minFreq);
const victim = bucket.keys().next().value;
bucket.delete(victim);
if (bucket.size === 0) this.buckets.delete(this.minFreq);
this.vals.delete(victim);
this.freq.delete(victim);
}
this.vals.set(key, value);
this.freq.set(key, 1);
if (!this.buckets.has(1)) this.buckets.set(1, new Map());
this.buckets.get(1).set(key, true);
this.minFreq = 1;
};
GoTested in our runner
package main
import "container/list"
type LFUCache struct {
capacity int
minFreq int
vals map[int]int
freq map[int]int
buckets map[int]*list.List // front is the LRU key
pos map[int]*list.Element
}
func Constructor(capacity int) LFUCache {
return LFUCache{
capacity: capacity,
vals: map[int]int{},
freq: map[int]int{},
buckets: map[int]*list.List{},
pos: map[int]*list.Element{},
}
}
func (this *LFUCache) addToBucket(key int, f int) {
b, ok := this.buckets[f]
if !ok {
b = list.New()
this.buckets[f] = b
}
this.pos[key] = b.PushBack(key)
}
func (this *LFUCache) touch(key int) {
f := this.freq[key]
bucket := this.buckets[f]
bucket.Remove(this.pos[key])
if bucket.Len() == 0 {
delete(this.buckets, f)
if this.minFreq == f {
this.minFreq = f + 1
}
}
this.freq[key] = f + 1
this.addToBucket(key, f+1)
}
func (this *LFUCache) get(key int) int {
if _, ok := this.vals[key]; !ok {
return -1
}
this.touch(key)
return this.vals[key]
}
func (this *LFUCache) put(key int, value int) {
if this.capacity == 0 {
return
}
if _, ok := this.vals[key]; ok {
this.vals[key] = value
this.touch(key)
return
}
if len(this.vals) >= this.capacity {
bucket := this.buckets[this.minFreq]
front := bucket.Front()
victim := front.Value.(int)
bucket.Remove(front)
if bucket.Len() == 0 {
delete(this.buckets, this.minFreq)
}
delete(this.vals, victim)
delete(this.freq, victim)
delete(this.pos, victim)
}
this.vals[key] = value
this.freq[key] = 1
this.addToBucket(key, 1)
this.minFreq = 1
}
C#Tested in our runner
using System.Collections.Generic;
public class LFUCache {
private int capacity;
private int minFreq;
private Dictionary<int, int> vals = new Dictionary<int, int>();
private Dictionary<int, int> freq = new Dictionary<int, int>();
// First node of each list is the LRU key
private Dictionary<int, LinkedList<int>> buckets = new Dictionary<int, LinkedList<int>>();
private Dictionary<int, LinkedListNode<int>> pos = new Dictionary<int, LinkedListNode<int>>();
public LFUCache(int capacity) {
this.capacity = capacity;
}
public int get(int key) {
if (!vals.ContainsKey(key)) return -1;
Touch(key);
return vals[key];
}
public void put(int key, int value) {
if (capacity == 0) return;
if (vals.ContainsKey(key)) {
vals[key] = value;
Touch(key);
return;
}
if (vals.Count >= capacity) {
var bucket = buckets[minFreq];
int victim = bucket.First.Value;
bucket.RemoveFirst();
if (bucket.Count == 0) buckets.Remove(minFreq);
vals.Remove(victim);
freq.Remove(victim);
pos.Remove(victim);
}
vals[key] = value;
freq[key] = 1;
AddToBucket(key, 1);
minFreq = 1;
}
private void Touch(int key) {
int f = freq[key];
var bucket = buckets[f];
bucket.Remove(pos[key]);
if (bucket.Count == 0) {
buckets.Remove(f);
if (minFreq == f) minFreq = f + 1;
}
freq[key] = f + 1;
AddToBucket(key, f + 1);
}
private void AddToBucket(int key, int f) {
if (!buckets.TryGetValue(f, out var b)) {
b = new LinkedList<int>();
buckets[f] = b;
}
pos[key] = b.AddLast(key);
}
}
Common mistakes
- Raising
minFreqon every touch, for exampleminFreq += 1unconditionally. Only move it when the emptied bucket was the minimum (if minFreq == f). Otherwise the minimum drifts above the real smallest counter. - Evicting from the most recent end of
buckets[minFreq]. Touches append to the end, so the front holds the least recent key. Pop the front, not the back. - Updating the value in
puton an existing key without touching it. An update counts as a use, so the counter and recency must change too. - Leaving
minFrequnchanged after the last key of the minimum bucket is evicted. The new key starts at counter 1, so setminFreq = 1on every insert. - Checking
size >= capacityafter inserting, or running eviction whencapacity == 0. With capacity 0,putmust return before it touches any structure. - In the brute force, comparing only the counter during eviction. Ties need the last-use time too, so
minby counter alone can evict the more recent key.
Edge cases
- Capacity 1: each new key evicts the only stored key, and the counter of the stored key does not matter.
geton a missing key returns -1 and changes no counter, no bucket, and nominFreq.puton an existing key updates the value and counts as a use, so that key is protected from the next eviction.- All keys tied on counter 1: eviction removes the least recently inserted key, which is the front of bucket 1.
- Key 0 and value 0 are valid inputs and must be stored like any other value.
- Capacity 0: every
putis ignored and everygetreturns -1.
Follow-ups interviewers ask
- What if every key has the same counter all the time? Does the design still work?
- Yes. Every key sits in one bucket, so the structure reduces to an LRU cache. Touching a key moves it to the end, and eviction still removes the front, so every operation stays O(1).
- Can you avoid a hand-written doubly linked list?
- Yes. An insertion-ordered set or map gives the same O(1) append, remove, and first-element operations. Python uses OrderedDict, Java uses LinkedHashSet, JavaScript uses Map, and Go and C# use their list types.
- What if the cache must be shared by several threads?
- Guard all four methods with one lock. A single operation updates several maps and buckets together, so splitting the lock can leave them inconsistent. Under the lock, each operation keeps its O(1) cost.
LFU Cache FAQ
What is the time complexity of LFU Cache?
Both get and put run in O(1) average time with frequency buckets. The brute force that scans the cache on eviction costs O(C) per put, where C is the capacity. The space is O(C) because the cache stores at most C keys.
Why use frequency buckets for LFU Cache?
Each counter changes by exactly one per use, so a key only moves between neighbouring buckets. That lets you track the minimum counter with one integer and find the victim without a scan.
Can LFU Cache be solved in O(1) extra space?
No. The cache must hold up to C keys and values, so the space is O(C). The bookkeeping adds a constant amount per stored key, so there is no way to drop below the cache's own size.
Why doesn't a heap solve LFU Cache?
A heap keyed on (counter, last use) gives O(log C) per update, because each touch changes a key's priority. The problem requires O(1) average time, so the bucket design is needed.
Is an ordered dictionary enough for the recency tie-break?
Yes, if you keep one ordered dictionary per counter value. Its insertion order gives the least recent key at the front, and removing a key from the middle is O(1).
Asked at
See which companies ask this — Pro
Related problems
- Find Median from Data Stream · same technique: Design (General/Specific)
- Design Search Autocomplete System · same technique: Design (General/Specific)
- All O`one Data Structure · same technique: Design (General/Specific)
- Design a Text Editor · same technique: Design (General/Specific)
- Range Module · same technique: Design (General/Specific)
- Word Squares · same pattern: Design Patterns
- Prefix and Suffix Search · same pattern: Design Patterns
- LRU Cache · same pattern: Design Patterns
- Min Stack · same pattern: Design Patterns
- Time Based Key-Value Store · same pattern: Design Patterns