Skip to main content
InterviewHubPRO
Section Overview
Q534

Question 534 of 536

Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 536)

100%
JavaScript & V8 Internals (536 Qs)•Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 536)

How do you implement an O(1) Least Recently Used (LRU) Cache in JavaScript?

senior LevelMost AskedCode ExampleFormsPerformanceSystem Design

In Simple Words: An LRU (Least Recently Used) Cache is a fixed-capacity data structure that evicts the least recently accessed item when capacity is reached, achieving $O(1)$ time complexity for both get and put operations by leveraging ES6 Map insertion-order properties or a doubly linked list with a hash map.

Approach 1: Modern JavaScript Implementation using Map (Optimal & Idiomatic)

JavaScript ES6 Map objects remember the original insertion order of the keys. When a key is read or updated, deleting and re-inserting it pushes it to the back (most recent). The first element returned by map.keys().next().value is always the least recently used element.

javascript
class LRUCacheMap {
  constructor(capacity) {
    this.capacity = capacity;
    this.cache = new Map();
  }

  get(key) {
    if (!this.cache.has(key)) return -1;

    // Refresh position to most recently used
    const val = this.cache.get(key);
    this.cache.delete(key);
    this.cache.set(key, val);
    return val;
  }

  put(key, value) {
    // If key already exists, delete it first to reset position
    if (this.cache.has(key)) {
      this.cache.delete(key);
    } else if (this.cache.size >= this.capacity) {
      // Evict least recently used (first key in iteration order)
      const oldestKey = this.cache.keys().next().value;
      this.cache.delete(oldestKey);
    }

    this.cache.set(key, value);
  }
}

Approach 2: Classic Doubly Linked List + Hash Map (Standard Data Structures Interview)

When interviewers restrict native Map behavior, use a custom doubly linked list with pseudo head and tail sentinel nodes for $O(1)$ node removal and insertion.

javascript
class Node {
  constructor(key, value) {
    this.key = key;
    this.value = value;
    this.prev = null;
    this.next = null;
  }
}

class LRUCache {
  constructor(capacity) {
    this.capacity = capacity;
    this.map = new Map();

    // Sentinel dummy head and tail
    this.head = new Node(0, 0);
    this.tail = new Node(0, 0);
    this.head.next = this.tail;
    this.tail.prev = this.head;
  }

  // Remove existing node from linked list: O(1)
  _remove(node) {
    node.prev.next = node.next;
    node.next.prev = node.prev;
  }

  // Insert node right after head (most recently used): O(1)
  _insert(node) {
    node.next = this.head.next;
    node.prev = this.head;
    this.head.next.prev = node;
    this.head.next = node;
  }

  get(key) {
    if (!this.map.has(key)) return -1;
    const node = this.map.get(key);
    this._remove(node);
    this._insert(node);
    return node.value;
  }

  put(key, value) {
    if (this.map.has(key)) {
      const node = this.map.get(key);
      node.value = value;
      this._remove(node);
      this._insert(node);
    } else {
      if (this.map.size >= this.capacity) {
        // Evict LRU node right before tail
        const lru = this.tail.prev;
        this._remove(lru);
        this.map.delete(lru.key);
      }
      const newNode = new Node(key, value);
      this.map.set(key, newNode);
      this._insert(newNode);
    }
  }
}

// Verification:
const lru = new LRUCache(2);
lru.put(1, 1); // cache is {1=1}
lru.put(2, 2); // cache is {1=1, 2=2}
console.log(lru.get(1)); // returns 1, marks 1 as MRU -> {2=2, 1=1}
lru.put(3, 3); // evicts key 2 -> cache is {1=1, 3=3}
console.log(lru.get(2)); // returns -1 (not found)
lru.put(4, 4); // evicts key 1 -> cache is {3=3, 4=4}
console.log(lru.get(1)); // returns -1 (not found)
console.log(lru.get(3)); // returns 3
console.log(lru.get(4)); // returns 4