Skip to content
Backend logic · Core · about 20 minutes

LRU cache

Implement createLRU(capacity). It returns an object with get(key), put(key, value) and size(). get returns the stored value, or null when the key is missing, and makes the key the most recently used. put stores or updates the value and makes the key the most recently used; when that leaves more than capacity keys, it removes the least recently used one. size() returns how many keys are stored. A stored value can be 0 or false. get and put should take constant time. In the tests an op [at, method, ...args] calls that method at virtual time at (ms); the answer lists what each call returned. put returns nothing, so the answer lists only get and size.

Start from

function createLRU(capacity) {
  // Return { get, put, size } that evicts the least recently used key.
}

Hints

Each hint gives away a little more. Open one only when you need it.

  1. Hint 1

    A Map remembers insertion order, and map.keys().next().value is the oldest key.

  2. Hint 2

    To mark a key as recent, delete it and set it again so it moves to the end.

  3. Hint 3

    Check map.has(key) for a miss; a stored 0 or false is falsy but present.

Solution

The app has this lab in JavaScript, TypeScript and Python. This page shows the JavaScript code.

From here on the page gives the method away. If you are still solving, go back to the hints.

JavaScript
function createLRU(capacity) {
  const map = new Map();
  return {
    get(key) {
      if (!map.has(key)) return null;
      const value = map.get(key);
      map.delete(key);
      map.set(key, value);
      return value;
    },
    put(key, value) {
      map.delete(key);
      map.set(key, value);
      if (map.size > capacity) map.delete(map.keys().next().value);
    },
    size() {
      return map.size;
    },
  };
}

What an interviewer looks for

Caches sit in front of most databases and APIs, and LRU is the default eviction rule. The question checks that you know a structure that is constant time for both lookups and recency.