Implement an LRU cache
An LRU (Least Recently Used) cache with a fixed capacity evicts the entry that was used least recently; in JavaScript a Map gives O(1) get and put, because it remembers insertion order: re-insert on access to mark as most recent, and evict map.keys().next().value (the oldest) when over capacity.
Operations
get(key): if present, move it to the most-recent position (delete and re-set) and return the value; otherwise returnundefined(or-1in the LeetCode version).put(key, value): delete the old entry if present, set it (now most recent), and if the size exceeds capacity, delete the first (least recent) key.
The classic data-structure answer
In languages without an ordered hash map, use a hash map + doubly linked list: the map gives O(1) lookup of list nodes, and the list gives O(1) move-to-front and remove-from-tail. Interviewers may ask for this to see you understand why it is O(1); the Map version is the idiomatic JavaScript answer.
Extensions
- TTL: store an expiry time with each entry and treat expired entries as missing.
- Size by weight (bytes instead of count).
has/peekthat do not update recency.- Eviction callback (
onEvict) for cleanup.
Where LRU caches are used
Memoisation with bounded memory, image and API response caches, database page caches, CDN edges, and browser caches.
Code example
1class LRUCache {2 #map = new Map();3 constructor(capacity) {4 if (capacity < 1) throw new RangeError("capacity must be at least 1");5 this.capacity = capacity;6 }78 get(key) {9 if (!this.#map.has(key)) return undefined;10 const value = this.#map.get(key);11 this.#map.delete(key); // move to most-recent position12 this.#map.set(key, value);13 return value;14 }1516 put(key, value) {17 if (this.#map.has(key)) this.#map.delete(key);18 this.#map.set(key, value);19 if (this.#map.size > this.capacity) {20 const oldest = this.#map.keys().next().value; // first key = least recently used21 this.#map.delete(oldest);22 }23 return this;24 }2526 peek(key) {27 return this.#map.get(key); // read without updating recency28 }2930 keys() {31 return [...this.#map.keys()]; // least -> most recent32 }33}3435const cache = new LRUCache(3);36cache.put("a", 1).put("b", 2).put("c", 3);37cache.get("a"); // "a" becomes most recent38cache.put("d", 4); // evicts "b", the least recently used39console.log(cache.keys()); // ["c", "a", "d"]40console.log(cache.get("b"), cache.get("c")); // undefined 341cache.put("e", 5); // evicts "a"42console.log(cache.keys()); // ["d", "c", "e"]4344// Bounded memoisation with an LRU cache45const lru = new LRUCache(100);46const slowSquare = (n) => lru.get(n) ?? (lru.put(n, n * n), n * n);47console.log(slowSquare(12), slowSquare(12)); // 144 144
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.