Design
Think of a cloakroom. Your ticket number takes the attendant straight to your coat, and the rail keeps coats in the order they were handed in. Two simple tools, each answering a different question fast.
2 · Watch
Design in 60 seconds
3 · Now you drive
LRU Cache
4 · Your turn
Start from this
class Cache {
// One structure finds things fast...
private byKey = new Map<number, Node>();
// ...and another keeps them in the order you need.
private order = new DoublyLinkedList();
use(key: number): void {
const node = this.byKey.get(key);
if (!node) return;
// Every call touches both, in O(1) each.
this.order.moveToEnd(node);
}
}Easy ways to go wrong
- Updating one structure and forgetting the other, so the map points at a node the list dropped.
- Scanning an array to find or remove a value, which makes the call O(n).
- Skipping the head and tail sentinels, then special-casing the empty list everywhere.
- Medium01
Min Stack
Pair each value with the smallest value below it.
Each value can carry the minimum of everything under it, so a pop never loses the answer.
- Time
- O(1)
- Space
- O(n)
Also works with Stack.
O(1) time · O(n) spaceclass MinStack { // Each entry keeps its value and the smallest value at or below it. private stack: [number, number][] = []; push(val: number): void { const min = this.stack.length ? Math.min(val, this.stack.at(-1)![1]) : val; this.stack.push([val, min]); } pop(): void { this.stack.pop(); } top(): number { return this.stack.at(-1)![0]; } getMin(): number { return this.stack.at(-1)![1]; } } - Medium02
LRU Cache
The one you just watched. Write it from memory.
You need a fast lookup and an order of use at once: a map plus a doubly linked list.
- Time
- O(1)
- Space
- O(capacity)
Also works with Linked List.
O(1) time · O(capacity) spaceclass Node { prev: Node | null = null; next: Node | null = null; constructor(public key: number, public value: number) {} } class LRUCache { // The map finds a node at once. The list keeps nodes from oldest to newest. private map = new Map<number, Node>(); private head = new Node(0, 0); // oldest end private tail = new Node(0, 0); // newest end constructor(private capacity: number) { this.head.next = this.tail; this.tail.prev = this.head; } get(key: number): number { const node = this.map.get(key); if (!node) return -1; // Using a key makes it the newest. this.remove(node); this.append(node); return node.value; } put(key: number, value: number): void { const old = this.map.get(key); if (old) this.remove(old); const node = new Node(key, value); this.map.set(key, node); this.append(node); if (this.map.size > this.capacity) { // The node next to the head is the one used longest ago. const oldest = this.head.next!; this.remove(oldest); this.map.delete(oldest.key); } } private remove(node: Node): void { node.prev!.next = node.next; node.next!.prev = node.prev; } private append(node: Node): void { node.prev = this.tail.prev; node.next = this.tail; this.tail.prev!.next = node; this.tail.prev = node; } } - Medium03
Time Based Key-Value Store
A map of lists, then a binary search inside one list.
Each key's timestamps arrive in order, so its list is already sorted for a binary search.
- Time
- O(log n)
- Space
- O(n)
Also works with Binary Search.
O(log n) time · O(n) spaceclass TimeMap { // Each key's values in the order they were set. Timestamps only grow. private store = new Map<string, [number, string][]>(); set(key: string, value: string, timestamp: number): void { if (!this.store.has(key)) this.store.set(key, []); this.store.get(key)!.push([timestamp, value]); } get(key: string, timestamp: number): string { const entries = this.store.get(key) ?? []; // Binary search for the last entry set at or before timestamp. let lo = 0; let hi = entries.length - 1; let answer = ""; while (lo <= hi) { const mid = (lo + hi) >> 1; if (entries[mid][0] <= timestamp) { answer = entries[mid][1]; lo = mid + 1; } else { hi = mid - 1; } } return answer; } } - Medium04
Insert Delete GetRandom O(1)
Swap the value you remove with the last one, so the array never has gaps.
A random pick needs an array, and a fast remove needs a map from value to its position.
- Time
- O(1)
- Space
- O(n)
Also works with Arrays & Hashing.
O(1) time · O(n) spaceclass RandomizedSet { // The values packed into an array, and where each one sits. private values: number[] = []; private index = new Map<number, number>(); insert(val: number): boolean { if (this.index.has(val)) return false; this.index.set(val, this.values.length); this.values.push(val); return true; } remove(val: number): boolean { const i = this.index.get(val); if (i === undefined) return false; // Move the last value into the gap, then drop the end. No shifting. const last = this.values.at(-1)!; this.values[i] = last; this.index.set(last, i); this.values.pop(); this.index.delete(val); return true; } getRandom(): number { return this.values[Math.floor(Math.random() * this.values.length)]; } }