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) returns the value stored for the key, or -1 if the key is not there. put(key, value) stores the value, replacing any old value for that key.

Each key has a use count, which every get or put on that key increases by one. When the cache is full and put brings a new key, it first removes the key with the smallest count. If several keys share that count, it removes the one used longest ago. Both methods must run in O(1) on average.

Example 1
Input: capacity 2; put(1, 1), put(2, 2), get(1), put(3, 3), get(2), get(3)
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
Input: capacity 2; put(1, 1), put(2, 2), put(1, 10), put(3, 3), get(1), get(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.
Solution

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) and put(2, 2) fill the cache, and each key has been used once. get(1) uses key 1 a second time. Now put(3, 3) needs room. Key 1 has been used twice and key 2 only once, so key 2 goes, and the later get(2) returns -1.

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 takes as long as the cache is big. And when several keys share the smallest count, the rule wants the one used longest ago, so the cache must also remember the order of use.

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.

Keys grouped by use count. After put(1, 1), put(2, 2) and get(1), the group for count 1 holds key 2 and the group for count 2 holds key 1. The smallest count is 1, so put(3, 3) evicts key 2, and the new key 3 joins the group for count 1.

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) has removed key 2, and the new key 3 has joined the group for count 1.

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 does with a key the cache already holds.

Where values and counts are kept

How does get find a value quickly? A HashMap from key to value, named values, answers in one step on average. A second map, counts, from key to use count, tells which group a key is in right now.

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 LinkedHashSet does all three. It is a hash set whose entries are also chained together in a doubly linked list, in the order they were added. Removing a key is a hash lookup plus unlinking it from its two neighbours, and iterator().next() returns the key added first.

A third map, byCount, goes from each use count to its LinkedHashSet. Using a key that has count c removes it from the set for c and adds it to the end of the set for c + 1. A key always enters a set at the end, so the front of each set holds the key used longest ago.

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, and updated at the only two moments it can change.

When a new key arrives, it has count 1 and nothing is lower, so minCount becomes 1. When a key moves from count c to c + 1 and leaves the group for c empty, and c was minCount, the smallest count becomes c + 1. That is where the key just went, and no key is left below it.

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 put gets a key the cache already holds? Then nothing is evicted: the value is replaced, and the put counts as a use, just like a get. In Example 2, put(1, 10) raises key 1 to count 2, so put(3, 3) evicts key 2, not key 1. A cache with capacity 0 can hold nothing, so its put returns at once.

Java Solution

The class has five parts, one for each piece of the approach:

  • values: the map from key to value, which get reads.
  • counts: the map from key to use count, so a key's group can be found.
  • byCount: the map from use count to the LinkedHashSet of keys with that count, oldest use first. A set that becomes empty is removed.
  • minCount: the smallest count in the cache. When the cache is full, put evicts the first key of the set for minCount.
  • touch: 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 raises minCount when that empties the group for minCount. get and an updating put both call it.

The main method runs both examples, a tie between two keys with the same count, a cache with room for one key, a cache with capacity 0, and 1,000 gets on one key.

Java
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:

Output
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) = -1 because key 2 was evicted, and the Update line shows key 1 kept with its new value, 10. Look at the Tie line next. Keys 1 and 2 were both used twice, but get(1) came before get(2), so key 1 was used longer ago. put(3, 3) evicted key 1, and get(1) returned -1.

The Capacity 1 line depends on minCount. get(1) moved key 1 to count 2 and emptied the group for count 1, so minCount rose from 1 to 2. put(2, 2) then evicted key 1 from the group for count 2.

Without that raise in touch, the cache breaks. With the line minCount++ removed, the program prints the first two lines and then stops in the Tie test with a NullPointerException. After get(2), the group for count 1 is gone, but minCount is still 1, so byCount.get(1) returns null.

The last line shows why empty sets are removed from byCount. After 1,000 gets, key 1 has count 1001, yet byCount keeps one group, not a thousand empty ones.

Complexity

Every get and put does a fixed number of map and set operations and never searches through the keys.

  • 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 LinkedHashSet and one add to another. Hash-based maps and sets do each of those in constant time on average.
  • Space: O(capacity). values and counts hold at most capacity keys. byCount holds each key in exactly one set and drops a set once it is empty, so it never has more groups than keys.

Evicting by order of use alone, without counts, is LRU Cache.