← Back to JavaScript, page 5

javascript-0087 · Hard senior

Implement an LRU (least recently used) cache with O(1) get and put. Why does a Map work, and how does the classic linked-list design compare?

An LRU cache evicts the least recently used entry when it is full. A JavaScript Map remembers insertion order, so deleting and re-inserting a key on each use keeps the oldest entry first, giving O(1) get and put without extra structures. The classic design pairs a hash map with a doubly linked list to move nodes in O(1), and both behave the same.

Full answer

A cache keeps recent results to avoid repeated work. A capacity limit forces a rule for what to throw away, and least recently used is a common choice: the entry that has gone unused the longest is evicted first. The interface is get(key), which returns the value and marks the entry as most recently used, and put(key, value), which inserts or updates and evicts if the capacity is exceeded.

The classic answer uses two structures. A hash map from key to node gives O(1) lookup. A doubly linked list orders nodes from most to least recently used. On a hit, the node is unlinked and moved to the front in O(1), because a doubly linked list can remove a node when it holds both neighbors. On overflow, the tail node is removed, and its key is deleted from the map.

In JavaScript there is a shorter route. A Map iterates in insertion order, and delete followed by set moves a key to the end. So the most recently used key is the last one and the least recently used is map.keys().next().value. All operations are O(1) on average. This is the design most interviewers accept in JavaScript, as long as the candidate can explain why it works and describe the linked-list version.

Details to handle: get on a missing key returns undefined (or a sentinel if undefined is a valid value), updating an existing key refreshes its position without evicting, and capacity must be a positive integer. Optional extras are a time-to-live, an eviction callback, and statistics for hits and misses.

Space is O(capacity). A single instance is not safe to share between workers without extra coordination, though a single-threaded event loop avoids races in one thread.

javascript
class LRUCache {
  #capacity;
  #map = new Map();

  constructor(capacity, onEvict = () => {}) {
    if (!Number.isInteger(capacity) || capacity < 1) throw new RangeError('capacity must be a positive integer');
    this.#capacity = capacity;
    this.onEvict = onEvict;
  }

  get(key) {
    if (!this.#map.has(key)) return undefined;
    const value = this.#map.get(key);
    this.#map.delete(key);
    this.#map.set(key, value); // now the most recently used
    return value;
  }

  put(key, value) {
    if (this.#map.has(key)) this.#map.delete(key);
    this.#map.set(key, value);
    if (this.#map.size > this.#capacity) {
      const [oldestKey, oldestValue] = this.#map.entries().next().value;
      this.#map.delete(oldestKey);
      this.onEvict(oldestKey, oldestValue);
    }
  }

  keys() {
    return [...this.#map.keys()]; // least to most recently used
  }
}

class LinkedLRU {
  constructor(capacity) {
    this.capacity = capacity;
    this.index = new Map();
    this.head = { next: null, prev: null }; // sentinel: most recent side
    this.tail = { next: null, prev: null }; // sentinel: least recent side
    this.head.next = this.tail;
    this.tail.prev = this.head;
  }
  #unlink(node) {
    node.prev.next = node.next;
    node.next.prev = node.prev;
  }
  #addFront(node) {
    node.next = this.head.next;
    node.prev = this.head;
    this.head.next.prev = node;
    this.head.next = node;
  }
  get(key) {
    const node = this.index.get(key);
    if (!node) return undefined;
    this.#unlink(node);
    this.#addFront(node);
    return node.value;
  }
  put(key, value) {
    const existing = this.index.get(key);
    if (existing) this.#unlink(existing);
    const node = existing ?? { key, value };
    node.value = value;
    this.#addFront(node);
    this.index.set(key, node);
    if (this.index.size > this.capacity) {
      const last = this.tail.prev;
      this.#unlink(last);
      this.index.delete(last.key);
    }
  }
  keys() {
    const result = [];
    for (let node = this.tail.prev; node !== this.head; node = node.prev) result.push(node.key);
    return result;
  }
}

const evicted = [];
const cache = new LRUCache(2, (key) => evicted.push(key));
cache.put('a', 1);
cache.put('b', 2);
console.log(cache.get('a'), cache.keys());
cache.put('c', 3); // evicts b, because a was just used
console.log(cache.get('b'), cache.keys(), evicted);
cache.put('a', 10); // update refreshes a, no eviction
console.log(cache.keys(), cache.get('a'), evicted);

try {
  new LRUCache(0);
} catch (error) {
  console.log(error.name);
}

function mulberry32(seed) {
  return () => {
    seed = (seed + 0x6d2b79f5) | 0;
    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}
const random = mulberry32(2026);
const mapVersion = new LRUCache(5);
const listVersion = new LinkedLRU(5);
let same = true;
for (let step = 0; step < 5000; step++) {
  const key = Math.floor(random() * 12);
  if (random() < 0.5) {
    mapVersion.put(key, step);
    listVersion.put(key, step);
  } else if (mapVersion.get(key) !== listVersion.get(key)) {
    same = false;
  }
  if (step % 500 === 0 && mapVersion.keys().join() !== listVersion.keys().join()) same = false;
}
console.log('Map version and linked-list version agree on 5000 random operations:', same);

Run with Node.js v24.22.1 as js-87.js; two runs gave identical output. Output: 1 [ 'b', 'a' ] undefined [ 'a', 'c' ] [ 'b' ] [ 'c', 'a' ] 10 [ 'b' ] RangeError Map version and linked-list version agree on 5000 random operations: true

Key points

  • LRU evicts the entry unused for the longest time.
  • Classic design: hash map plus doubly linked list gives O(1) get and put.
  • Map insertion order makes delete then set a move-to-end operation.
  • Updating an existing key refreshes its position and must not evict.
  • Handle undefined values, capacity validation, and optionally TTL and eviction callbacks.

Common mistakes

  • Forgetting to refresh the key's position on a get, which turns the cache into FIFO.
  • Evicting when updating an existing key at full capacity.
  • Using an array with indexOf and splice, which makes every operation O(n).
  • Returning undefined for a miss when undefined is also a valid stored value, with no way to tell them apart.

Follow-ups

  • How would you add a time-to-live to each entry?
  • How would you make the cache safe to share between several workers?
  • How do LFU (least frequently used) and LRU differ, and when would LFU be better?

Tips

  • Explain the Map trick and why it gives O(1), then offer to draw the linked-list version.
  • Test the update case: putting an existing key must not evict anything.
  • Mention how misses and undefined values are handled.