Scrivio Interview library
DesignIntermediate8 min read · updated 12 November 2026

Design an in-memory LFU (least frequently used) cache with O(1) get and put in Java. Describe the data structures and how ties are broken.

An O(1) LFU cache uses two hash maps and one number: a map from key to a node holding the value and its use count, a map from each count to the keys with that count kept in recency order (a LinkedHashSet or a doubly linked list), and the current minimum count. Each access moves the key from list f to list f + 1, raising the minimum if list f empties; eviction removes the oldest key in the minimum-count list, which breaks ties by least recent use. For production, Caffeine's W-TinyLFU gives better hit rates with bounded memory, so a custom cache needs a strong reason.

Why this question is asked

Caches decide what to keep when memory is limited, and the eviction policy is what makes one cache hit 95 percent of the time and another 60 percent. LFU, least frequently used, keeps the entries that were used most often, which suits workloads where popularity is stable. Interviewers ask for an O(1) LFU because the obvious designs are O(log n) or O(n), and getting to O(1) needs a clever combination of structures. In this answer, we will recap LFU and the naive designs, build the O(1) structure, walk through get, put and eviction, write it in Java, trace an example, and discuss why a real service would use Caffeine instead.

1A Quick Recap of LFU and Why the Naive Designs Are Slow

An LFU cache counts how many times each key has been accessed. When the cache is full and a new key arrives, it evicts the key with the lowest count. Many keys may share the lowest count, so we also need a tie-breaker; the usual choice is to evict the least recently used among them.

The naive design keeps a count per key in a HashMap and scans all entries to find the minimum on eviction, which is O(n). A better attempt keeps entries in a priority queue or a TreeMap ordered by count, which gives O(log n) updates, because every access changes a count and must reposition the entry. To reach O(1), we need to avoid any ordering work beyond moving a key one step at a time.

2The Structure: Two Maps and a Minimum

The key observation is that an access always increases a count by exactly one. So instead of keeping all keys sorted by count, we group keys by count. The structure has three parts. The first is a HashMap from key to a node holding the value and the key's current count. The second is a HashMap from count to the set of keys with that count, kept in the order they arrived at that count; a LinkedHashSet does this, or a hand-written doubly linked list. The third is minFreq, the smallest count that currently has any keys.

Notice why each part is O(1). Finding a key's value and count is a hash lookup. Moving a key from count f to count f + 1 is a removal from one LinkedHashSet and an insertion into another, both O(1) on average. Finding the eviction victim is a lookup of the set for minFreq and taking its first element, which is the oldest, so the least recently used among the least frequently used.

State of a capacity-3 cache after some accesses
CountKeys at this count, oldest firstNote
1c, dminFreq = 1, so c is the next victim
2bb was read once
4aa was read three times
Each key appears in exactly one count list; the key map also records each key's count.

3How get, put and Eviction Work

get(key) looks up the node. If it is missing, it returns null. Otherwise it touches the key: it removes the key from the set for its count f, adds it to the set for f + 1, and increments the node's count. If the set for f is now empty and f was minFreq, then minFreq becomes f + 1, because the key we just moved is now at f + 1 and nothing else is lower.

put(key, value) for an existing key updates the value and touches it like get. For a new key, if the cache is full it evicts first: it takes the first key in the set for minFreq, removes it from that set and from the key map. Then it inserts the new key with count 1 into the set for 1 and sets minFreq to 1, since a brand-new key always has the lowest possible count. That reset is why minFreq never needs to be searched for.

Step throughput(key, value) for a new key
  1. Is the cache at capacity?
    YesEvict firstNoSkip eviction
  2. Find the set for minFreqits first key is the oldest of the least used
  3. Remove the victimfrom the set and from the key map
  4. Insert the new key with count 1add it to the set for count 1
  5. Set minFreq = 1a new key always has the lowest count

5 steps in order. Play them, or step through them one at a time.

4Writing It in Java

Here is a compact version using LinkedHashSet for the per-count lists. It is not thread safe, which we come back to later.

Java
final class LfuCache<K, V> {
private static final class Node<V> { V value; int freq = 1; Node(V v) { value = v; } }
private final int capacity;
private final Map<K, Node<V>> nodes = new HashMap<>();
private final Map<Integer, LinkedHashSet<K>> byFreq = new HashMap<>();
private int minFreq;
LfuCache(int capacity) { this.capacity = capacity; }
V get(K key) {
Node<V> n = nodes.get(key);
if (n == null) return null;
touch(key, n);
return n.value;
}
void put(K key, V value) {
if (capacity <= 0) return;
Node<V> n = nodes.get(key);
if (n != null) { n.value = value; touch(key, n); return; }
if (nodes.size() == capacity) {
LinkedHashSet<K> lowest = byFreq.get(minFreq);
K victim = lowest.iterator().next(); // oldest key with the lowest count
lowest.remove(victim);
if (lowest.isEmpty()) byFreq.remove(minFreq);
nodes.remove(victim);
}
nodes.put(key, new Node<>(value));
byFreq.computeIfAbsent(1, f -> new LinkedHashSet<>()).add(key);
minFreq = 1;
}
private void touch(K key, Node<V> n) {
int f = n.freq;
LinkedHashSet<K> set = byFreq.get(f);
set.remove(key);
if (set.isEmpty()) {
byFreq.remove(f);
if (minFreq == f) minFreq = f + 1;
}
n.freq = f + 1;
byFreq.computeIfAbsent(f + 1, x -> new LinkedHashSet<>()).add(key);
}
}

Notice that computeIfAbsent is safe here, because its mapping function only creates a set and does not modify the map itself.

5Tracing an Example

A short trace with capacity 2 shows the tie-breaking and the minimum at work.

Java
LfuCache<String, Integer> c = new LfuCache<>(2);
c.put("a", 1); // a:1 minFreq 1
c.put("b", 2); // a:1, b:1 minFreq 1
c.get("a"); // 1 a:2, b:1 minFreq 1
c.put("c", 3); // evicts b (count 1) a:2, c:1, minFreq 1
c.get("b"); // null
c.get("c"); // 3 a:2, c:2 minFreq 2
c.put("d", 4); // tie at count 2: evicts a, the older of a and c
c.get("a"); // null
c.get("c"); // 3

Notice the last eviction. Both a and c had count 2, and a reached count 2 before c did, so a was first in the set for count 2 and was evicted. That is the least-recently-used tie-break.

6Why Production Code Usually Uses Caffeine

Plain LFU has known weaknesses. Counts never decay, so a key that was hugely popular last week can sit in the cache forever while today's popular keys keep getting evicted, a problem called cache pollution. New keys start at count 1 and are the first victims, so a burst of new popular items struggles to get in. And keeping an exact count per key costs memory.

Caffeine, the standard Java caching library, uses W-TinyLFU. New entries go into a small window governed by recency. When an entry leaves the window, a compact frequency sketch, a few bits per counter in a count-min sketch that is periodically halved so old popularity fades, decides whether it is more popular than the entry the main area would evict, and only then is it admitted. This gives hit rates close to the best possible on many real workloads, with bounded memory and full thread safety. So a hand-written LFU needs a strong reason, such as a constrained environment or an interview.

7Follow-up questions

How would you make the LFU cache thread safe?

The simplest way is to guard get and put with one lock, because every get also mutates the count structures. That is correct but serialises all access. Caffeine avoids this by recording reads in buffers and applying them to the policy in batches, so readers rarely block. For an exercise, a ReentrantLock around both methods is the honest answer.

Why a LinkedHashSet rather than a LinkedList for each count?

A LinkedHashSet removes a given key in O(1) because it finds the entry by hash. Removing a given element from java.util.LinkedList is O(n), since it must search for it. A hand-written doubly linked list where the key's node holds its own prev and next pointers is also O(1) and uses less memory.

When is LRU better than LFU?

When popularity shifts quickly, such as news articles or session data, recency predicts the next access better than long-term frequency, and LRU adapts immediately. LFU shines when a stable set of items is popular for a long time. W-TinyLFU combines both, which is why it does well across workloads.

8Conclusion

In this answer, we built an LFU cache with O(1) get and put from a map of key to node with value and count, a map of count to a LinkedHashSet of keys in recency order, and the current minimum count. An access moves a key from count f to f + 1 and raises the minimum when list f empties; a new key resets the minimum to 1; and eviction takes the oldest key in the minimum list, so ties go to the least recently used. For production, Caffeine's W-TinyLFU gives better hit rates, ages old popularity and is thread safe.

What to say in the interviewAbout 90 seconds aloud

Open with

I would use two hash maps and a counter. The first map goes from key to a node with the value and its access count. The second goes from count to the keys with that count, kept in insertion order, so a LinkedHashSet, or a doubly linked list if I write my own nodes.

Then, if they want more

And I keep minFreq, the lowest count present. On get, I find the node, remove the key from the set for its count f, add it to the set for f plus one, and if set f became empty and f was the minimum, the minimum becomes f plus one.

On put of an existing key I update the value and do the same touch.

On put of a new key, if the cache is full I take the first key from the minFreq set, which is the least frequently used and, among those, the least recently used, and remove it from both maps; then I insert the new key with count 1 and set minFreq to 1, since a new key is always the minimum.

Everything is a hash operation, so O(1) on average. For a real service I would use Caffeine instead: its W-TinyLFU uses a frequency sketch with aging plus a recency window, which avoids plain LFU's pollution by old popular keys and is thread safe.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Design an in-memory LFU (least frequently used) cache with O(1) get and put in Java....": https://scrivio-interview-library.netlify.app/java/algorithms-and-data-structures/ff34b0a5dd/