LFU Cache solution explained
An LFU cache evicts the key that has been used the fewest times, and breaks ties by evicting the least recently used of those keys. The O(1) design keeps three things in step: a map from key to value and use count, a map from each use count to the keys with that count in recency order, and the smallest use count currently present. Every get and put moves one key from bucket c to bucket c + 1, which is constant time.
By Evin JohnPublished 9 min read
The task, restated
Build a cache that holds at most capacity keys. get(key) returns the stored value, or -1 if the key is absent. put(key, value) stores the value; if the key already exists, it updates the value. Both a successful get and any put on an existing key count as one use of that key. When the cache is full and a new key arrives, first remove the key with the smallest use count. If several keys share that smallest count, remove the one whose last use is oldest. Both operations should run in O(1) average time.
| Call | Returns | Cache after (key: uses) | Note |
|---|---|---|---|
| put(a, 1) | a: 1 | ||
| put(b, 2) | a: 1, b: 1 | ||
| get(a) | 1 | a: 2, b: 1 | a now has two uses |
| put(c, 3) | a: 2, c: 1 | full, b has the fewest uses and goes | |
| get(b) | -1 | a: 2, c: 1 | b was evicted |
| get(c) | 3 | a: 2, c: 2 | tie at two uses |
| put(d, 4) | c: 2, d: 1 | a and c tie; a was used longer ago, so a goes | |
| get(a) | -1 | c: 2, d: 1 |
Pin down three details before writing anything. Does a put that updates an existing key count as a use? In the common version it does. What happens with capacity 0? Every put is ignored and every get returns -1. And does a freshly inserted key start at one use? Yes, and that detail is what keeps the min-uses pointer simple.
How it differs from LRU
LRU Cache ranks keys on one axis, how recently they were touched, so one ordered list is enough. LFU ranks on two: use count first, recency second. A key read a hundred times survives a burst of new keys that each got read once, which LRU would not allow. The price is bookkeeping. Most candidates who know LRU well get stuck on LFU at the same point: they find the victim fine, but cannot find the next victim in O(1) after the counts shift. The buckets and the min-uses pointer are the answer to that.
- Interviewers usually ask LRU first and LFU as the harder follow-up, often in the same loop or as a stretch question.
- They watch how you keep several maps consistent. Every operation edits two or three structures, and a missing delete shows up as a wrong eviction many steps later.
- They may ask for real-world tradeoffs. Pure LFU can keep a key that was hot last week forever; production caches add aging or use hybrids, and saying so earns credit.
A slow design: scan for the victim
Store each key's value, use count and the tick of its last use, where tick is a counter that rises on every operation. Get and update are O(1). Eviction scans every key for the smallest (uses, tick) pair, which is O(n). This is a perfectly good first answer to say aloud, and it is also the reference implementation used to test the fast design.
class LFUCacheSlow:
def __init__(self, capacity):
self.capacity = capacity
self.data = {} # key -> [value, uses, last_tick]
self.tick = 0
def get(self, key):
self.tick += 1
if key not in self.data:
return -1
entry = self.data[key]
entry[1] += 1
entry[2] = self.tick
return entry[0]
def put(self, key, value):
self.tick += 1
if self.capacity <= 0:
return
if key in self.data:
entry = self.data[key]
entry[0] = value
entry[1] += 1
entry[2] = self.tick
return
if len(self.data) == self.capacity:
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.tick]The O(1) design
Group keys by use count. Bucket 1 holds every key used once, bucket 2 every key used twice, and so on, and each bucket keeps its keys in the order they entered it, oldest first. A key enters a bucket exactly when it reaches that count, which is also its most recent use, so oldest first inside a bucket means least recently used first. The victim is always the first key in the bucket for the smallest count. A min_uses variable remembers which count that is.
- Touch a key (get hit or put on an existing key)Remove it from bucket c, append it to bucket c + 1, and store c + 1 as its count. If bucket c is now empty and c was min_uses, set min_uses to c + 1; the key you just moved lives there, so that bucket cannot be empty.
- Insert a new key when fullPop the oldest key from bucket min_uses and delete it from the key map. No need to recompute the minimum, because the next line resets it.
- Insert a new keyStore it with count 1, append it to bucket 1, and set min_uses to 1. Nothing can have fewer uses than a brand new key.
Python's OrderedDict gives each bucket O(1) append, O(1) removal of any key and O(1) pop of the oldest key. JavaScript's Set keeps insertion order and also deletes any element in O(1) on average, and its first element is set.values().next().value. In a language without either, each bucket is a doubly linked list with a map from key to node, which is exactly what the LRU design uses, once per count.
from collections import OrderedDict, defaultdict
class LFUCache:
def __init__(self, capacity):
self.capacity = capacity
self.entries = {} # key -> [value, uses]
self.by_uses = defaultdict(OrderedDict) # uses -> keys, oldest first
self.min_uses = 0
def _touch(self, key):
uses = self.entries[key][1]
bucket = self.by_uses[uses]
del bucket[key]
if not bucket:
del self.by_uses[uses]
if self.min_uses == uses:
self.min_uses = uses + 1
self.by_uses[uses + 1][key] = None
self.entries[key][1] = uses + 1
def get(self, key):
if key not in self.entries:
return -1
self._touch(key)
return self.entries[key][0]
def put(self, key, value):
if self.capacity <= 0:
return
if key in self.entries:
self.entries[key][0] = value
self._touch(key)
return
if len(self.entries) == self.capacity:
lowest = self.by_uses[self.min_uses]
victim, _ = lowest.popitem(last=False)
if not lowest:
del self.by_uses[self.min_uses]
del self.entries[victim]
self.entries[key] = [value, 1]
self.by_uses[1][key] = None
self.min_uses = 1class LFUCache {
constructor(capacity) {
this.capacity = capacity;
this.vals = new Map();
this.counts = new Map();
this.buckets = new Map();
this.minUses = 0;
}
bump(key) {
const c = this.counts.get(key);
const bucket = this.buckets.get(c);
bucket.delete(key);
if (bucket.size === 0) {
this.buckets.delete(c);
if (this.minUses === c) this.minUses = c + 1;
}
this.counts.set(key, c + 1);
if (!this.buckets.has(c + 1)) this.buckets.set(c + 1, new Set());
this.buckets.get(c + 1).add(key);
}
get(key) {
if (!this.vals.has(key)) return -1;
this.bump(key);
return this.vals.get(key);
}
put(key, value) {
if (this.capacity <= 0) return;
if (this.vals.has(key)) {
this.vals.set(key, value);
this.bump(key);
return;
}
if (this.vals.size === this.capacity) {
const lowest = this.buckets.get(this.minUses);
const victim = lowest.values().next().value;
lowest.delete(victim);
if (lowest.size === 0) this.buckets.delete(this.minUses);
this.vals.delete(victim);
this.counts.delete(victim);
}
this.vals.set(key, value);
this.counts.set(key, 1);
if (!this.buckets.has(1)) this.buckets.set(1, new Set());
this.buckets.get(1).add(key);
this.minUses = 1;
}
}Deleting empty buckets is optional for correctness in the Python version, since a defaultdict recreates them, but it keeps memory proportional to the number of keys rather than to the highest count ever reached. In JavaScript it also keeps the victim lookup honest: an empty Set would return undefined as its first element.
Why min_uses never needs a search
There are only three moments when the minimum count can change. A touch moves one key up by one; if that empties the minimum bucket, the new minimum is exactly one higher, because the moved key now sits there. An eviction removes a key from the minimum bucket, but it is always followed by an insert. An insert adds a key with count 1, which is the smallest possible count. So the pointer is always right without looking at other buckets. Walking through this argument is often the moment an interviewer decides you understand the design rather than remember it.
Time and space
| Design | get | put on a full cache | Extra space |
|---|---|---|---|
| Count plus timestamp, scan to evict | O(1) | O(n) | O(n) |
| Min-heap of (count, tick) with lazy entries | O(log n) amortized | O(log n) amortized | O(n) plus stale entries |
| Count buckets with ordered sets and min pointer | O(1) average | O(1) average | O(n) |
Edge cases
- Capacity 0: put returns without storing anything. Without that guard, the eviction branch tries to pop from an empty bucket.
- Capacity 1: every new key evicts the single resident, whatever its count.
- Updating an existing key on a full cache must not evict anything; check for the key before checking fullness.
- A get on a missing key changes nothing, not even recency.
- Long runs on one key: its count grows without limit, which is fine for integers in both languages within any test you will see.
Mistakes to avoid
- Checking fullness before checking whether the key already exists, so an update evicts a different key.
- Forgetting to reset min_uses to 1 after inserting a new key.
- Recomputing the minimum by scanning all buckets, which quietly turns put back into O(n).
- Breaking ties by insertion time instead of last use. The bucket order handles this only if a touched key is appended to the end of its new bucket.
- Treating get on a missing key as a use, or a put on an existing key as not a use, without asking which the interviewer wants.
- Leaving empty Sets in the JavaScript bucket map, then reading undefined as the victim.
How to explain it out loud
Fictional example
- Candidate
- I'll keep the value and use count per key, and for each count a bucket of keys ordered from least to most recently used. Plus one number, the smallest count that has keys.
- Candidate
- A hit moves the key from bucket c to the end of bucket c plus one. If bucket c empties and it was the minimum, the minimum becomes c plus one, since the key I moved is there.
- Candidate
- On insert into a full cache I pop the front of the minimum bucket, add the new key to bucket one and set the minimum to one. Everything is constant time on average.
Related problems
LRU Cache is the one-axis version and the natural warm-up. Design HashMap asks you to build the map this design leans on, which is a common follow-up when an interviewer wants to see what O(1) average really depends on. Dijkstra's algorithm is another exercise in keeping a lookup table and an ordering structure in agreement, with a heap in place of buckets.
Natively as a study partner
Design questions like this reward talking through the invariant, and that is easy to rehearse with Natively on Mac or Windows. It transcribes your explanation so you can reread where it got vague, and in practice it can take a screenshot of the prompt and outline a design with code for you to compare with your own. Its Code hint action is there when you get stuck on the min-uses argument. See the AI interview assistant page for how sessions work.
Questions people ask
How do you implement an LFU cache in O(1)?
Keep a map from key to value and use count, a map from each count to its keys in recency order, and the smallest count in use. A get or put moves one key from bucket c to bucket c + 1, and eviction pops the oldest key from the smallest bucket.
What is the difference between LRU and LFU caches?
LRU evicts the key that was used longest ago. LFU evicts the key used the fewest times and only uses recency to break ties, so a frequently read key survives bursts of new keys.
How is the minimum frequency kept up to date?
A touch can raise it by exactly one, when the smallest bucket empties, because the moved key lands in the next bucket. Inserting a new key resets it to 1, so no search is ever needed.
Does put on an existing key count as a use?
In the common version of the problem, yes: updating a value counts as a use and moves the key up one bucket. Confirm it with the interviewer.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
