LFU Cache With O(1) Operations
Build a least-frequently-used cache with constant-time get and put using frequency buckets and doubly linked lists.
Code
class CacheNode<K, V> {
public previous: CacheNode<K, V> | null = null;
public next: CacheNode<K, V> | null = null;
public constructor(
public readonly key: K,
public value: V,
public frequency: number,
) {}
}
class FrequencyList<K, V> {
private head: CacheNode<K, V> | null = null;
private tail: CacheNode<K, V> | null = null;
public size = 0;
public addFront(node: CacheNode<K, V>): void {
node.previous = null;
node.next = this.head;
if (this.head !== null) this.head.previous = node;
this.head = node;
if (this.tail === null) this.tail = node;
this.size += 1;
}
public remove(node: CacheNode<K, V>): void {
if (node.previous !== null) node.previous.next = node.next;
else this.head = node.next;
if (node.next !== null) node.next.previous = node.previous;
else this.tail = node.previous;
node.previous = null;
node.next = null;
this.size -= 1;
}
public removeLast(): CacheNode<K, V> | null {
if (this.tail === null) return null;
const node = this.tail;
this.remove(node);
return node;
}
}
export class LfuCache<K, V> {
private readonly entries = new Map<K, CacheNode<K, V>>();
private readonly frequencies = new Map<number, FrequencyList<K, V>>();
private lowestFrequency = 0;
public constructor(private readonly capacity: number) {
if (!Number.isInteger(capacity) || capacity < 1) {
throw new RangeError("capacity must be a positive integer");
}
}
public get size(): number {
return this.entries.size;
}
public get(key: K): V | undefined {
const node = this.entries.get(key);
if (node === undefined) return undefined;
this.touch(node);
return node.value;
}
public peek(key: K): V | undefined {
return this.entries.get(key)?.value;
}
public put(key: K, value: V): this {
const existing = this.entries.get(key);
if (existing !== undefined) {
existing.value = value;
this.touch(existing);
return this;
}
if (this.entries.size >= this.capacity) this.evict();
const node = new CacheNode(key, value, 1);
this.entries.set(key, node);
this.listFor(1).addFront(node);
this.lowestFrequency = 1;
return this;
}
public delete(key: K): boolean {
const node = this.entries.get(key);
if (node === undefined) return false;
this.removeNode(node);
return true;
}
private touch(node: CacheNode<K, V>): void {
const oldFrequency = node.frequency;
const oldList = this.frequencies.get(oldFrequency);
if (oldList === undefined) {
throw new Error("cache invariant violated");
}
oldList.remove(node);
if (oldList.size === 0) {
this.frequencies.delete(oldFrequency);
if (this.lowestFrequency === oldFrequency) {
this.lowestFrequency = oldFrequency + 1;
}
}
node.frequency = oldFrequency + 1;
this.listFor(node.frequency).addFront(node);
}
private evict(): void {
const list = this.frequencies.get(this.lowestFrequency);
if (list === undefined) return;
const node = list.removeLast();
if (node === null) return;
this.entries.delete(node.key);
if (list.size === 0) this.frequencies.delete(this.lowestFrequency);
}
private removeNode(node: CacheNode<K, V>): void {
const list = this.frequencies.get(node.frequency);
if (list === undefined) {
throw new Error("cache invariant violated");
}
list.remove(node);
this.entries.delete(node.key);
if (list.size === 0) this.frequencies.delete(node.frequency);
}
private listFor(frequency: number): FrequencyList<K, V> {
let list = this.frequencies.get(frequency);
if (list === undefined) {
list = new FrequencyList<K, V>();
this.frequencies.set(frequency, list);
}
return list;
}
}
const cache = new LfuCache<string, number>(2);
cache.put("a", 1).put("b", 2);
console.log(cache.get("a"));
cache.put("c", 3);
console.log(cache.get("b"), cache.peek("a"), cache.get("c"));
cache.put("d", 4);
console.log(cache.get("a"), cache.get("c"), cache.get("d"));
console.log(cache.size);How the snippet works
The moving parts are the classes CacheNode, FrequencyList and LfuCache.
Invalid states are rejected up front: it throws RangeError and Error instead of continuing with bad data.
Top-level bindings cache hold the demo state — nothing sits inside a function scope.
What to watch for
- The guard
this.tail === nullshort-circuits the flow with an earlyreturnwhen its condition holds.
Applying it
Import LfuCache from the file and call it — the rest of the code is implementation detail.
Statements that matter
return this.entries.get(key)?.value;
private readonly frequencies = new Map<number, FrequencyList<K, V>>();
throw new RangeError("capacity must be a positive integer");
Interactive Tools for This Topic
Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.HAR Waterfall AnalyzerInspect HTTP Archive (HAR 1.2) JSON files locally to summarize total requests, status codes, MIME types, slowest calls, and timing waterfalls.Cache-Control BuilderCompose a valid Cache-Control header from directives such as no-store, private, max-age, and immutable.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.
FAQ
- Is there a failure path for bad input?
- It throws `RangeError` and `Error` before any real work runs, via the guard `this.tail === null` — handle it at the call site or let it propagate deliberately.
- Does it depend on any third-party library?
- No third-party library is referenced; the standard library covers it. Its state lives in module-level bindings: `cache`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.