Java Design Program · CD21
Implement an LFU Cache in Java
An LRU cache forgets what was not used recently. An LFU cache forgets what was used least often, so a key that is popular overall survives a quiet moment.
Problem Statement
Design an LFU cache with a fixed capacity, get(key) (return -1 if missing) and put(key, value). Every get or put of a key increases its use count.
When the cache is full, evict the key with the lowest count; if several keys share it, evict the one that was used longest ago.
Input/Output Examples
capacity 2: put(1), put(2), get(1), put(3)Outputkey 2 is evictedExplanation: key 1 has count 2, key 2 only 1.keys 1 and 3 both have count 2; put(4)Outputkey 1 is evictedExplanation: key 1 reached count 2 before key 3.get(2) after its evictionOutput-1Explanation: the key is no longer cached.Visual Explanation
- put(1), put(2)count 112both start at 1
- get(1)count 12count 21key 1 moves up
- put(3)count 12evict oldest of the lowest count key 2 out
- Aftercount 13count 21minCount = 1
- Donecache = {1, 3}
Tracking the lowest non-empty count in a variable means eviction never has to search for it.
Approaches
Both approaches give identical results on 5,000 random test runs. The first does every operation in constant time; the second is shorter but logarithmic.
Approach 1: Frequency Buckets (Recommended)
Idea: keep three maps (key to value, key to count and count to a LinkedHashSet of keys) plus the current minimum count.
- On a hit, move the key from bucket
cto bucketc + 1; if bucketcbecomes empty and was the minimum, increase the minimum. - On a put to a full cache, remove the first key of the minimum bucket.
- Insert the new key into bucket 1 and set the minimum to 1.
Time: O(1) · Space: O(n). for both get and put; n is the capacity.
Approach 2: TreeSet Ordered by Count and Time
Idea: store entries in a TreeSet sorted by (count, last-use time); the first entry is the victim.
- Give every use a new tick from a counter.
- On a hit, remove the entry, increase its count, update its tick and add it back.
- On a full put, call
pollFirst().
Time: O(log n) · Space: O(n).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Frequency Buckets (Recommended)
The standard optimal answer; every step is a hash or linked-set operation.
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
public class LfuCacheBuckets {
// O(1) LFU: key -> value, key -> count, and count -> keys in the order they reached that count
static class LfuCache {
private final int capacity;
private final Map<Integer, Integer> values = new HashMap<>();
private final Map<Integer, Integer> counts = new HashMap<>();
private final Map<Integer, LinkedHashSet<Integer>> buckets = new HashMap<>();
private int minCount;
LfuCache(int capacity) { this.capacity = capacity; }
int get(int key) {
if (!values.containsKey(key)) return -1;
touch(key);
return values.get(key);
}
void put(int key, int value) {
if (capacity == 0) return;
if (values.containsKey(key)) {
values.put(key, value);
touch(key);
return;
}
if (values.size() == capacity) {
LinkedHashSet<Integer> least = buckets.get(minCount);
int victim = least.iterator().next(); // oldest key with the lowest count
least.remove(victim);
values.remove(victim);
counts.remove(victim);
}
values.put(key, value);
counts.put(key, 1);
buckets.computeIfAbsent(1, c -> new LinkedHashSet<>()).add(key);
minCount = 1; // a new key always has the lowest count
}
private void touch(int key) { // move key from bucket c to bucket c + 1
int c = counts.get(key);
counts.put(key, c + 1);
LinkedHashSet<Integer> bucket = buckets.get(c);
bucket.remove(key);
if (bucket.isEmpty() && c == minCount) minCount++;
buckets.computeIfAbsent(c + 1, k -> new LinkedHashSet<>()).add(key);
}
}
public static void main(String[] args) {
LfuCache cache = new LfuCache(2);
cache.put(1, 10);
cache.put(2, 20);
System.out.println("get(1) = " + cache.get(1)); // key 1 now used twice
cache.put(3, 30); // full: key 2 has the lowest count
System.out.println("get(2) = " + cache.get(2) + ", get(3) = " + cache.get(3));
cache.put(4, 40); // keys 1 and 3 both used twice: 1 is older
System.out.println("get(1) = " + cache.get(1) + ", get(3) = " + cache.get(3) + ", get(4) = " + cache.get(4));
}
}
get(1) = 10 get(2) = -1, get(3) = 30 get(1) = -1, get(3) = 30, get(4) = 40
Time complexity: O(1) · Space complexity: O(n).
Approach 2: TreeSet Ordered by Count and Time
Easier to get right in an interview; remove the entry before changing its sort fields.
import java.util.HashMap;
import java.util.Map;
import java.util.TreeSet;
public class LfuCacheTreeSet {
// Keep entries in a TreeSet sorted by (count, last-use time): the first entry is the one to evict
static class LfuCache {
private static final class Entry {
final int key;
int value, count;
long time;
Entry(int key, int value, long time) { this.key = key; this.value = value; this.count = 1; this.time = time; }
}
private final int capacity;
private final Map<Integer, Entry> byKey = new HashMap<>();
private final TreeSet<Entry> order = new TreeSet<>((a, b) ->
a.count != b.count ? Integer.compare(a.count, b.count) : Long.compare(a.time, b.time));
private long clock;
LfuCache(int capacity) { this.capacity = capacity; }
int get(int key) {
Entry e = byKey.get(key);
if (e == null) return -1;
bump(e);
return e.value;
}
void put(int key, int value) {
if (capacity == 0) return;
Entry e = byKey.get(key);
if (e != null) {
e.value = value;
bump(e);
return;
}
if (byKey.size() == capacity) {
Entry victim = order.pollFirst();
byKey.remove(victim.key);
}
e = new Entry(key, value, clock++);
byKey.put(key, e);
order.add(e);
}
private void bump(Entry e) {
order.remove(e); // remove before changing the sort fields
e.count++;
e.time = clock++;
order.add(e);
}
}
public static void main(String[] args) {
LfuCache cache = new LfuCache(2);
cache.put(1, 10);
cache.put(2, 20);
System.out.println("get(1) = " + cache.get(1)); // key 1 now used twice
cache.put(3, 30); // full: key 2 has the lowest count
System.out.println("get(2) = " + cache.get(2) + ", get(3) = " + cache.get(3));
cache.put(4, 40); // keys 1 and 3 both used twice: 1 is older
System.out.println("get(1) = " + cache.get(1) + ", get(3) = " + cache.get(3) + ", get(4) = " + cache.get(4));
}
}
get(1) = 10 get(2) = -1, get(3) = 30 get(1) = -1, get(3) = 30, get(4) = 40
Time complexity: O(log n) · Space complexity: O(n).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Frequency Buckets | O(1) | O(n) |
| TreeSet Ordered by Count and Time | O(log n) | O(n) |
The bucket version does a constant number of map and set operations per call. The tree version pays O(log n) to reorder an entry on each use.
Interview Tips and Recommended Approach
- Clarify the tie rule before coding; most versions evict the least recently used among the least frequent.
- Reset the minimum to 1 on every new key; that is the step candidates most often miss.
- Handle capacity 0; a put must not try to evict from an empty cache.
- Compare with LRU: LFU resists one-off scans but can keep keys that were popular long ago.
Recommended Approach: Frequency Buckets
Why: it meets the usual O(1) requirement, and each map has one clear job, which makes the code easy to explain line by line.