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 return undefined (or -1 in 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/peek that 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

js
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 }
7
8 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 position
12 this.#map.set(key, value);
13 return value;
14 }
15
16 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 used
21 this.#map.delete(oldest);
22 }
23 return this;
24 }
25
26 peek(key) {
27 return this.#map.get(key); // read without updating recency
28 }
29
30 keys() {
31 return [...this.#map.keys()]; // least -> most recent
32 }
33}
34
35const cache = new LRUCache(3);
36cache.put("a", 1).put("b", 2).put("c", 3);
37cache.get("a"); // "a" becomes most recent
38cache.put("d", 4); // evicts "b", the least recently used
39console.log(cache.keys()); // ["c", "a", "d"]
40console.log(cache.get("b"), cache.get("c")); // undefined 3
41cache.put("e", 5); // evicts "a"
42console.log(cache.keys()); // ["d", "c", "e"]
43
44// Bounded memoisation with an LRU cache
45const 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.

Open in study app