LFU Cache
Build a cache that, when full, removes the key used the fewest times, and among ties the one used longest ago.
Design a least frequently used (LFU) cache: a store for integer keys and values with a fixed capacity. get(key)put(key, value)
Each key has a use count, which every getputput
Example 1
Output: get(1) = 1, get(2) = -1, get(3) = 3
Explanation: after get(1), key 1 has count 2 and key 2 has count 1, so put(3, 3) evicts key 2.
Example 2
Output: get(1) = 10, get(2) = -1
Explanation: put(1, 10) replaces the value of key 1 and counts as a use, so key 1 has count 2 and put(3, 3) evicts key 2.
The Idea
A cache is a small, fast store that keeps copies of data that is slow to fetch, such as rows from a database or pages from a server. It has room for only so many items, so when it is full and a new item arrives, an old one has to go. Which one? A sensible guess is the item used the fewest times, since it seems the least likely to be needed again.
Follow Example 1, with room for two keys. put(1, 1)put(2, 2)get(1)put(3, 3)get(2)
With two keys, comparing counts is easy. With thousands of keys, which one has the smallest count? Looking through all of them on every put
Both questions get easy if the keys are sorted into groups by use count, and each group keeps its keys in the order they were last used, oldest first. Look at the picture below.
On the left, the group labelled count 1 holds key 2, used once, and the group labelled count 2 holds key 1, used twice. The smallest count is 1, so the key to evict is the oldest key in that group: key 2. On the right, put(3, 3)
So eviction never has to search. It goes to the group for the smallest count and takes the key at its front. Each use of a key moves it up one group, to the end of the group for the next count.
Solution Approach
Turning the groups into code means settling four things: where the values and counts are kept, what holds each group in order, how to know the smallest count without searching, and what put
Where values and counts are kept
How does getHashMapvaluescounts
Keeping each group in order
What should hold a group? It must do three things fast: add a key at the end, remove a key from anywhere when that key is used, and give back the key at the front. A plain list can find a key in the middle only by walking through it, one key at a time.
Java's LinkedHashSetiterator().next()
A third map, byCountLinkedHashSet
Knowing the smallest count
Which group should eviction look in? Checking every count would be a search again. A sorted structure such as a priority queue would avoid the search, but with n keys each change to it takes O(log n) steps. Instead, the smallest count is kept in a variable, minCount
When a new key arrives, it has count 1 and nothing is lower, so minCountminCount
Nothing else can change the smallest count. Using a key never lowers a count, and an eviction is always followed by a new key with count 1.
Updating a key that is already there
What if putputgetput(1, 10)put(3, 3)put
Java Solution
The class has five parts, one for each piece of the approach:
: the map from key to value, whichvalues reads.get : the map from key to use count, so a key's group can be found.counts : the map from use count to thebyCount of keys with that count, oldest use first. A set that becomes empty is removed.LinkedHashSet : the smallest count in the cache. When the cache is full,minCount evicts the first key of the set forput .minCount : records one use of a key. It moves the key from the set for count c to the end of the set for c + 1, and raisestouch when that empties the group forminCount .minCount and an updatingget both call it.put
The main
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
public class LFUCache {
private final int capacity;
private final Map<Integer, Integer> values = new HashMap<>(); // key -> value
private final Map<Integer, Integer> counts = new HashMap<>(); // key -> use count
// use count -> keys with that count, in order of last use (oldest first)
private final Map<Integer, LinkedHashSet<Integer>> byCount = new HashMap<>();
private int minCount = 0;
public LFUCache(int capacity) {
this.capacity = capacity;
}
public int get(int key) {
if (!values.containsKey(key)) {
return -1;
}
touch(key);
return values.get(key);
}
public void put(int key, int value) {
if (capacity == 0) {
return;
}
if (values.containsKey(key)) { // an update counts as a use
values.put(key, value);
touch(key);
return;
}
if (values.size() == capacity) {
LinkedHashSet<Integer> lowest = byCount.get(minCount);
int evict = lowest.iterator().next(); // least frequent, then least recent
lowest.remove(evict);
if (lowest.isEmpty()) {
byCount.remove(minCount);
}
values.remove(evict);
counts.remove(evict);
}
values.put(key, value);
counts.put(key, 1);
byCount.computeIfAbsent(1, c -> new LinkedHashSet<>()).add(key);
minCount = 1; // a new key always has the smallest count
}
// Move key from the group for count c to the end of the group for count c + 1.
private void touch(int key) {
int c = counts.get(key);
LinkedHashSet<Integer> group = byCount.get(c);
group.remove(key);
if (group.isEmpty()) {
byCount.remove(c);
if (c == minCount) {
minCount++; // the key just went to c + 1
}
}
counts.put(key, c + 1);
byCount.computeIfAbsent(c + 1, x -> new LinkedHashSet<>()).add(key);
}
public static void main(String[] args) {
LFUCache cache = new LFUCache(2);
cache.put(1, 1);
cache.put(2, 2);
int a = cache.get(1);
cache.put(3, 3);
System.out.println("Example 1: get(1) = " + a + ", get(2) = " + cache.get(2)
+ ", get(3) = " + cache.get(3));
cache = new LFUCache(2);
cache.put(1, 1);
cache.put(2, 2);
cache.put(1, 10); // update: key 1 now used twice
cache.put(3, 3);
System.out.println("Update: get(1) = " + cache.get(1) + ", get(2) = "
+ cache.get(2) + ", get(3) = " + cache.get(3));
cache = new LFUCache(2);
cache.put(1, 1);
cache.put(2, 2);
cache.get(1);
cache.get(2); // both used twice, key 1 used longer ago
cache.put(3, 3);
System.out.println("Tie: get(1) = " + cache.get(1) + ", get(2) = "
+ cache.get(2) + ", get(3) = " + cache.get(3));
cache = new LFUCache(1);
cache.put(1, 1);
cache.get(1); // the group for count 1 is now empty
cache.put(2, 2);
System.out.println("Capacity 1: get(1) = " + cache.get(1) + ", get(2) = "
+ cache.get(2));
cache = new LFUCache(0);
cache.put(1, 1);
System.out.println("Capacity 0: get(1) = " + cache.get(1));
cache = new LFUCache(1);
cache.put(1, 1);
for (int i = 0; i < 1000; i++) {
cache.get(1);
}
System.out.println("1000 gets: count of key 1 = " + cache.counts.get(1)
+ ", groups kept = " + cache.byCount.size());
}
}
Running it prints:
Example 1: get(1) = 1, get(2) = -1, get(3) = 3
Update: get(1) = 10, get(2) = -1, get(3) = 3
Tie: get(1) = -1, get(2) = 2, get(3) = 3
Capacity 1: get(1) = -1, get(2) = 2
Capacity 0: get(1) = -1
1000 gets: count of key 1 = 1001, groups kept = 1
In the Example 1 line, get(2) = -1get(1)get(2)put(3, 3)get(1)
The Capacity 1 line depends on minCountget(1)minCountput(2, 2)
Without that raise in touchminCount++NullPointerExceptionget(2)minCountbyCount.get(1)null
The last line shows why empty sets are removed from byCountbyCount
Complexity
Every getput
- Time: O(1) on average for get and put. Each call does a few lookups in the three maps, at most one remove from a
and one add to another. Hash-based maps and sets do each of those in constant time on average.LinkedHashSet - Space: O(capacity).
andvalues hold at mostcounts keys.capacity holds each key in exactly one set and drops a set once it is empty, so it never has more groups than keys.byCount
Evicting by order of use alone, without counts, is