Skip to content

Build an LRU cache

Working knowledgeBuild alongTypeScriptYou need: hash maps, linked lists
What you’ll build: A least-recently-used cache with O(1) get and set, built from a hash map and a doubly linked list in six steps, and tested against a second implementation.list doubly linked, dummy endsmap key → nodeO(1) get, set, deleteevict least recent at the backtest 10,000 ops against a reference
Step 1 of 6

Start a doubly linked list

Make a folder with a package.json that sets "type": "module", so Node treats your .ts files as ES modules.

list.ts holds two classes. A ListNode stores a key, a value and two pointers, prev and next. A LinkedList starts with two dummy nodes, head and tail, pointing at each other, and addFront slots a node in straight after head.

WHY

The cache needs to keep keys in order of use and move any one of them in constant time. A doubly linked list can unhook a node it already holds in O(1), because the node knows both neighbours. The dummy ends mean the first and last real nodes are never special cases: every real node always has a prev and a next.

package.jsonnew+5−0
Added: {
Added: "name": "lru-cache",
Added: "private": true,
Added: "type": "module"
Added: }
list.tsnew+41−0
Added: // One entry in the list. It knows its neighbour on each side.
Added: export class ListNode<K, V> {
Added: key: K;
Added: value: V;
Added: prev: ListNode<K, V> | null = null;
Added: next: ListNode<K, V> | null = null;
Added:
Added: constructor(key: K, value: V) {
Added: this.key = key;
Added: this.value = value;
Added: }
Added: }
Added:
Added: // A doubly linked list with a dummy node at each end, so every real
Added: // node always has a prev and a next, and no case needs its own branch.
Added: export class LinkedList<K, V> {
Added: private head = new ListNode<K, V>(undefined as K, undefined as V);
Added: private tail = new ListNode<K, V>(undefined as K, undefined as V);
Added:
Added: constructor() {
Added: this.head.next = this.tail;
Added: this.tail.prev = this.head;
Added: }
Added:
Added: // Put a node straight after head: the front of the list.
Added: addFront(node: ListNode<K, V>): void {
Added: node.prev = this.head;
Added: node.next = this.head.next;
Added: this.head.next!.prev = node;
Added: this.head.next = node;
Added: }
Added:
Added: // Keys from front to back, for printing.
Added: keys(): K[] {
Added: const out: K[] = [];
Added: for (let n = this.head.next!; n !== this.tail; n = n.next!) {
Added: out.push(n.key);
Added: }
Added: return out;
Added: }
Added: }
demo.tsnew+7−0
Added: import { LinkedList, ListNode } from './list.ts';
Added:
Added: const list = new LinkedList<string, number>();
Added: for (const key of ['A', 'B', 'C']) {
Added: list.addFront(new ListNode(key, 0));
Added: console.log(list.keys().join(' '));
Added: }

Where to go next

Was this tutorial useful?Your vote tells us what to improve next.
Did a step not work, or something unclear?