Skip to curriculum
Jump to the editor

20.4. An LFU cache, compared with LRU

Hard
Topics

This question is in

20. Caches and buffers
35–50 min

An LRU cache (problem 20.3) evicts whatever was used longest ago. That is a poor choice when a few entries are used all the time and a stream of others are used once: one pass through a long list pushes the site logo, the current user and the translation table out of the cache. An LFU cache (least frequently used) counts how often each entry is used and evicts the one with the smallest count, so popular entries survive a scan.

Write an LFUCache class in lfu-cache.js. Like a good LRU, it must do every get and set in constant time.

Signature

JAVASCRIPT
class LFUCache {
  constructor(capacity, onEvict)  // capacity: a positive integer; onEvict(key, value) optional
  get size()
  get(key)          // the value, or undefined; counts one use
  peek(key)         // the value, or undefined; counts nothing
  has(key)          // true or false; counts nothing
  frequency(key)    // how many uses key has, or 0
  set(key, value)   // new key: 1 use; existing key: one more use; returns the cache
  delete(key)       // true if it was there
  keys()            // the keys in the order they would be evicted
  clear()
}

Requirements

  1. capacity must be a positive integer (RangeError); onEvict, when given, must be a function (TypeError).
  2. A new key starts with 1 use. Each get or set of an existing key adds 1. has, peek and misses count nothing. frequency of a missing key is 0.
  3. When a new key arrives in a full cache, the entry with the fewest uses is evicted; among entries with the same count, the least recently used one. Room is made before the new key is added, so it is never its own victim.
  4. Setting an existing key updates its value and evicts nothing.
  5. keys() lists the keys in eviction order: fewest uses first, and within a count, least recently used first.
  6. onEvict(key, value) is called for each evicted entry, after it has been removed. delete, overwriting and clear are not evictions.
  7. delete returns whether the key was there and frees a place. A deleted key that comes back starts again at 1.
  8. An entry holding undefined is an entry, and get on it counts. Keys are compared like Map keys.
  9. Counts never decrease: an entry used many times long ago stays ahead of newer entries with fewer uses.
  10. get and set take constant time: 200,000 operations with many evictions on a cache of 20,000 entries finish well within the time limit.

Examples

JAVASCRIPT
const cache = new LFUCache(2);
cache.set("logo", "L");
cache.get("logo"); cache.get("logo");   // logo: 3 uses
cache.set("photo-1", 1);                // photo-1: 1 use
cache.set("photo-2", 2);                // evicts photo-1 (fewest uses); LRU would evict logo
cache.keys();                           // ["photo-2", "logo"]
JAVASCRIPT
const tie = new LFUCache(2, (key) => console.log("evicted", key));
tie.set("a", 1).set("b", 2);            // both 1 use; a is older
tie.set("c", 3);                        // logs "evicted a"
tie.frequency("b");                     // 1
JAVASCRIPT
new LFUCache(1).set("x", 1).set("y", 2).has("x");   // false

Environment

  • Plain JavaScript in a browser page; the tests create new LFUCache(…) from lfu-cache.js.
  • Any built-in is allowed. One test runs 200,000 random operations, half of them misses, so searching all entries for the smallest count on each eviction fails on time.
  • Out of scope: ageing counts over time, weights per entry, and expiry.

Hints

  1. If you group keys by their count, where is the next victim, and what do you need to remember to find that group at once?
  2. Inside one group, what kind of collection keeps keys in the order they arrived and removes any one of them in constant time?
  3. When a key moves from count 2 to count 3, when does the smallest count change?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…